Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Parse.com REST API with query in node.js - how to use data-encode from CURL

I am trying to replicate the example of the parse.com rest API below:

curl -X GET \
  -H "X-Parse-Application-Id: APP_ID" \
  -H "X-Parse-REST-API-Key: API_KEY" \
  -G \
  --data-urlencode 'where={"playerName":"John"}' \
  https://api.parse.com/1/classes/GameScore

So, based on an example found on Stackoverflow, I implemented the function:

var https = require("https");
exports.getJSON = function(options, onResult){

    var prot = options.port == 443 ? https : http;
    var req = prot.request(options, function(res){
        var output = '';
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            output += chunk;
        });

        res.on('end', function() {
            var obj = JSON.parse(output);
            onResult(res.statusCode, obj);
        });
    });

    req.on('error', function(err) {
    });

    req.end();
};

which I call like that :

var options = {
host: 'api.parse.com',
port: 443,
path: '/1/classes/GameScore',
method: 'GET',
headers: {
    'X-Parse-Application-Id': 'APP_ID',
    'X-Parse-REST-API-Key': 'APP_KEY'
}
};

rest.getJSON(options,
    function(statusCode, result)
    {
        // I could work with the result html/json here.  I could also just return it
        //console.log("onResult: (" + statusCode + ")" + JSON.stringify(result));
        res.statusCode = statusCode;
        res.send(result);
    });

My question is, how do I send the "--data-urlencode 'where={"playerName":"Sean Plott","cheatMode":false}' bit? I tried appending it to the path by setting the path in the options like that: '/1/classes/GameScore?playerName=John, but that didn't work, I received all the GameScore, not the ones from John

like image 809
Cyril Gaillard Avatar asked Jan 20 '13 02:01

Cyril Gaillard


1 Answers

I tried appending it to the path by setting the path in the options like that: /1/classes/GameScore?playerName=John

It seems to be expecting where as the key/name with the value the entire JSON value:

/1/classes/GameScore?where=%7B%22playerName%22%3A%22John%22%7D

You can get this with querystring.stringify():

var qs = require('querystring');

var query = qs.stringify({
    where: '{"playerName":"John"}'
});

var options = {
    // ...
    path: '/1/classes/GameScore?' + query,
    // ...
};

// ...

Optionally with JSON.stringify() to format the value from object:

var query = qs.stringify({
    where: JSON.stringify({
        playerName: 'John'
    })
});
like image 195
Jonathan Lonowski Avatar answered Sep 18 '22 01:09

Jonathan Lonowski