Primus.io intercepting data on the server

296 views Asked by At

I am using Primus.io with primus-emit, on an Express 4 server.

I'm trying to find a way to hook into every message sent/received, including heartbeats, in order to track my active users, for another module of the application. (This is done using a Redis sorted set).

Since spark.on('data') isn't giving me anything, because everything is going through primus-emit, I was thinking of trying to write my own Primus plugin, or middleware for this, but I can't quite figure out how to get from a packet (in a plugin), or req, res (in middleware code), to a spark. As I am setting accountNumber on the spark object, in primus.on('connection').

So what I'm looking for is for the server side code, which will allow me to intercept any data passing on active sparks, just to be able to push spark.accountNumber to Redis.

PS. maybe I'm going about this the wrong way, so any hints appreciated. Essentially another part of my system needs to be aware of the active users, and I'm using Redis for this.

Thanks!!

1

There are 1 answers

0
naartjie On

So I asked for advice on irc.freenode.net and this is the advice I got from the nice folk on #primus: No need for any plugin/middleware jazz. The easiest way to solve it is by attaching to the internal 'incoming::data' event, like so:

primus.on('connection', function(spark) {
    spark.on('incoming::data', function(data) {
         // ... update redis set with 'connected' users here
    });

    // ... run all other code related to the spark as per usual here
});