Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Poll REST service with Node.js

Tags:

node.js

I'm working on a service that would poll Foursquare for certain check-ins every minute or so and save/update the results in a NoSQL database. Is the best approach to wrap an http.request with setInterval and then aggregate the chunked response using the data event emitter? I plan to use the end emitter to parse the JSON and push into a NoSQL DB when the request is complete. Thoughts?

like image 511
occasl Avatar asked Aug 23 '12 17:08

occasl


People also ask

What is poll in node JS?

Long polling in Node JS is a mechanism in which the client sends data to the server, but the server only responds until it has received complete data. Simultaneously, the client's link is open, and it is waiting for the server to reply with data before sending another query.

What is polling in REST API?

The Polling API is used to retrieve the reporting data from a request. The Polling API endpoint will respond to successful requests with compressed gzip. The response must be uncompressed to retrieve the data. Note: The Asynchronous API is generally available for all Responsys customers.

What is long polling in node JS?

As mentioned before, Node JS Long Polling Example is a process in which the client sends to the server; however, the server provides feedback after it has got full-proof information. Simultaneously, the client's connection is open and it is waiting to send a new query only after the server responds with the data.

How is polling implemented in Javascript?

Polling ImplementationThe executePoll function returns a promise and will run recursively until a stopping condition is met. The poll function takes 4 variables as arguments: fn : This is the function we will execute over a given interval. Typically this will be an API request.


1 Answers

There might be better ways, but I ended up just using event emitters to process the REST response as follows:

var fourSquareGet = {
    host: 'api.foursquare.com',
    port: 443,
    path: '/v2/venues/search?ll=33.88,-119.19&query=burger*',
    method: 'GET'
};
setInterval(function () {
    var reqGet = https.request(fourSquareGet, function (res) {
        var content;

        res.on('data', function (chunk) {
            content += chunk;
        });
        res.on('end', function () {
            // remove 'undefined that appears before JSON for some reason
            content = JSON.parse(content.substring(9, content.length));
            db.checkins.save(content.response.venues, function (err, saved) {
                if (err || !saved) throw err;
            });
            console.info("\nSaved from Foursquare\n");
        });
    });

    reqGet.end();
    reqGet.on('error', function (e) {
        console.error(e);
    });
}, 25000);

However, I'm not sure why I had parse out "undefined" from the JSON I received from foursquare.

like image 180
occasl Avatar answered Oct 10 '22 22:10

occasl