How to get spark instance on using Primus middleware

251 views Asked by At

I have setup a Primus websocket service as below.

http = require('http');
server = http.createServer();

Primus = require('primus');
primus = new Primus(server, {
  transformer: 'websockets',
  pathname: 'ws'
});

primus.on('connection', function connection(spark) {
  console.log("client has connected");
  spark.write("Herro Client, I am Server");
  spark.on('data', function(data) {
    console.log('PRINTED FROM SERVER:', data);
    spark.write('receive '+data)
  });
  spark.on('error', function(data) {
    console.log('PRINTED FROM SERVER:', data);
    spark.write('receive '+data)
  });
});



server.listen(5431);
console.log("Server has started listening");

It works fine. In above code, I use spark.write to send response message to users. Now I want to convert it to be used in a middleware. The code becomes as below:

primus.use('name', function (req, res, next) {
  doStuff();
});

in the doStuff() method, how I can get the spark instance to send message back to clients?

1

There are 1 answers

0
Prashanth Chandra On BEST ANSWER

The readme is slightly vague about this, but middleware only deals with the HTTP request.

Primus has two ways of extending the functionality. We have plugins but also support middleware. And there is an important difference between these. The middleware layers allows you to modify the incoming requests before they are passed in to the transformers. Plugins allow you to modify and interact with the sparks. The middleware layer is only run for the requests that are handled by Primus.

To achieve what you want, you'll have to create a plugin. It's not much more complicated than middleware.

primus.plugin('herro', {
  server: function(primus, options) {
    primus.on('connection', function(spark) {
      spark.write('Herro Client, I am Server')
    })
  },
  client: function(primus, options) {}
})  

For more info, see the Plugins section of the readme.