Sunday, 7 May 2017

Publish as API call and Subscribe as Clients in NodeJS

I am trying to understand how would my logic would fit on Pub/Sub. I see everywhere one client becomes a publisher and another becomes a Subscriber. The can chat in real-time and all. But my scenario is a bit different. I don't want any client to publish a message or so.

Instead, I want to make an API call and pass all the data for example from this url: http://www.example.com/test.json?param1=john&param2=doe to all the Subscriber.

The url above contains all the data and its pushed to X webpage where all the visitors visit, so When Clients visit this page: http://example.com/home They should get subscribed and get new updated real-time data pushed.

Here the idea is to Make all Mobile/Desktop/PC Browser as a client and make Server API call as Publisher of API data to Subscriber.

I really dont understand or find an example on how to achieve this?

The Flow I am looking for: API data publish to ---> http://localhost:8000/home Visitors who visit this page: http://localhost:8000/home they get data.

mycode in nodejs

var redis = require("redis");
var sub = redis.createClient(), pub = redis.createClient();
var msg_count = 0;

sub.on("subscribe", function (channel, count) {
    pub.publish("a nice channel1", "I am sending a message.");
    pub.publish("channel1", "I am sending a second message.");
    pub.publish("channel1", "I am sending my last message.");
});
sub.subscribe("channel1"); 

In the code above I want to change pub.publish() to something like:

pub.publish("channel1",apidata);

I also have the code that makes an Ajax call and gets the data. But I am using

setInterval(functionname,500);

which I guess makes the point of publish/subscribe useless. Because I get the data every half a second and then push it to the channel. I guess idea of publish/subscribe is to have an open connection and update user when new data arrives.

my API code

var http = require("http");

setInterval(test,500);
function test (){
    http.get("url", function(res) {
        var body = ''; // Will contain the final response
        // Received data is a buffer.
        // Adding it to our body
        res.on('data', function(data){
            body += data;
        });
        // After the response is completed, parse it and log it to the console
        res.on('end', function() {
            var parsed = JSON.parse(body);
            console.log(parsed);
            //Push Data as a Publisher to Channel X
        });
    })
    // If any error has occured, log error to console
        .on('error', function(e) {
            console.log("Got error: " + e.message);
        });

}

I am lost here. How do I get this things to work?



via Murlidhar Fichadia

No comments:

Post a Comment