0
votes

This is my Cloud Code Function:

Parse.Cloud.define("nearby", function (request, response) {
    nearby(request.params.sourceId, {
      success: function(answer) {
          var values = Object.keys(answer.end_result).map(function(key) {
              nearby = answer.end_result[key];

              nearby.near = new Parse.User({id:nearby.nearId})

              return nearby;
          });

          response.success(values);
      },
      error: function(error) {
        response.error(error);
      }
    });
})

Calling it from REST API

curl -X POST   -H "X-Parse-Application-Id: ..."  -H "X-Parse-REST-API-Key: ..."  -H "Content-Type: application/json"  -d '{ "sourceId": "jQsulDGk8Z" }'  https://api.parse.com/1/functions/nearby | python -m json.tool

returns a JSON, as expected:

{
    "result": [
        {
            "distance": 3,
            "near": {
                "__type": "Object",
                "className": "_User",
                "objectId": "aPWY5YP89A"
            },
            "nearId": "aPWY5YP89A",
            "sourceId": "jQsulDGk8Z",
            "updateAt": {
                "__type": "Date",
                "iso": "2015-08-18T14:48:28.344Z"
            }
        },
        {
            "distance": 2,
            "near": {
                "__type": "Object",
                "className": "_User",
                "objectId": "GHm78KVb9r"
            },
            "nearId": "GHm78KVb9r",
            "sourceId": "jQsulDGk8Z",
            "updateAt": {
                "__type": "Date",
                "iso": "2015-08-18T14:48:22.738Z"
            }
        }
    ]
}

How can I return fully populated user object instead of just in code created pointer? Since the Parse.User query is async, simply blocking and waiting for the object to populate does not work when you have multiple, variable number of user objectId's to query from.

I need some kind of synchronisation I'd assume on all the possible user queries.

1
You've tagged the question for promises, so have you tried using them ? - Wain
@Wain could you please provide a sample code for how to fit promises for this use case? - Maxim Veksler
Please show the source of function nearby(). Need to see if it returns a promise. Also, please describe the data being queried in nearby. Column names and types (important: is there a pointer to _User in that table?) - danh
@danh here is the actual copy & paste from the current version deployed in cloud code gist.github.com/maximveksler/59f95a4a66232df51eed. The structure of the nearby table is subject to changes, will making source & near a reference instead of a Pointer will help to solve the problem? - Maxim Veksler

1 Answers

0
votes

The happy news is that your NearBy model includes pointer to the user table. The end of that pointer can be eagerly fetched by include-ing it in the NearBy query...

function queryNearby(userId, sourceColumn, nearColumn, callback) {
    var query = new Parse.Query(NearBy);
    query.include("near");
    // ...

There's some less happy news, but not immediately unhappy: if another query -- or another asynch operation -- had been required, you would have had a headache building it at 2-3 levels of callback indirection. Your idea about promises is right. Consider restructuring your functions to always return promises and to use parse's promises returned from their SDK.

Edit To elaborate on the use of promises, here's an example of your code modified to use promises.

The idea is, rather than passing around callback functions and nesting calls N levels deep for N consequtive asynch operations, we have functions that create and return promises.

Now the function nearby returns a promise because it returns the promise returned by the function queryNearBySourceId. If you follow the chain further, that function returns a promise, too. Ultimately the function findNearby returns the promise returned by Parse.Query.find(). Notice how no function passes or invokes a callback function.

// call this function like this:
// nearby("some_source_id").then(function(result) {}, function(error) {});
// the result passed to the resolution function will be the object returned by nearby()

function nearby(sourceId) {
    return queryNearBySourceId(sourceId).then(function(answer) {
        // see the end of function queryNearby: I modified it to answer a single object
        var nearbyId_answer = answer;
        var nearId_runtime = answer.runtime_seen_updates;
        var end_result = {}

        _.each(sourceId_answer, function(value, key) {
            end_result[key] = value
        });

        _.each(nearbyId_answer, function(value, key) {
            if (!(key in end_result)) {
                end_result[key] = value
            }
        });

        return {"end_result" : end_result, 
                "sourceId_answer" : sourceId_answer, 
                "sourceId_runtime" : sourceId_runtime, 
                "nearbyId_answer" : nearbyId_answer, 
                "nearId_runtime" : nearId_runtime
                };
    });
}

function queryNearBySourceId(sourceId) {
    // console.error("******** queryNearby -- queryNearBySourceId")
    return queryNearby(sourceId, "source", "near")
}

function queryNearByNearId(nearId) {
    // console.error("******** queryNearby -- queryNearByNearId")
    return queryNearby(nearId, "near", "source")
}

function queryNearby(userId, sourceColumn, nearColumn) {
    // console.error("queryNearby(" + userId + "," + sourceColumn + "," + nearColumn + ")")
    var user = new Parse.User({id:userId});
    var lastValid = moment().subtract(5, 'minutes').toDate();
    return findNearby(user, lastValid, nearColumn).then(function(results) {
        // Model: { near : distance }
        var answer = {}
        // Model: { near : updateAt }
        var runtime_seen_updates = {}

        for (var i = 0; i < results.length; i++) {
            var nearby_entry = results[i];
            var source = nearby_entry.get(sourceColumn)
            var sourceId = source.id
            var distance = nearby_entry.get("distance")
            var updateAt = nearby_entry.updatedAt
            var o = { "sourceId" : sourceId, "near" : near, "distance" : distance, "updateAt" : updateAt }

            // console.error("queryNearby :: " + JSON.stringify(o))

            // Our goal is to find the most recent entry
            if (nearId in runtime_seen_updates) {
                // console.error("queryNearby (in runtime_seen_updates) :: " + nearId + "=" + JSON.stringify(o))
                runtime_seen_updates_updateAt = runtime_seen_updates[nearId]
                if (runtime_seen_updates_updateAt < updateAt) {
                    runtime_seen_updates[nearId] = updateAt
                    answer[nearId] = o
                }
            } else {
                // console.error("queryNearby (first) :: " + nearId + "=" + JSON.stringify(o))
                runtime_seen_updates[nearId] = updateAt
                answer[nearId] = o
            }
        }
        // rather than returning two objects, I added the 'runtime_seen_updates' attribute to the answer object
        answer.runtime_seen_updates = runtime_seen_updates;

        return answer;
    }, function(error) {
        alert("Error: " + error.code + " " + error.message);
        return error;
    });
}

function findNearby(user, date, nearColumn) {
    var query = new Parse.Query(NearBy);    
    query.equalTo(sourceColumn, user); // be we search which devices saw us.
    query.greaterThan("updatedAt", date);
    query.descending("updatedAt");
    query.include(nearColumn);  // important!
    return query.find();
 }

While editing, I noticed a few ways to further improve this code, but I limited myself to refactoring for promises because I wanted you to recognize the single idea change in the original.