Overlook Motel
Overlook Motel

Reputation: 181

Route socket.io messages to express routes

I'm looking to integrate socket.io into an express app.

sails.js has a really nice feature where express routes can also be called via socket.io messages.

However, sails is a bit more than I need in other respects. I'm looking for a way to have socket.io requests forwarded to express routes without having to use the whole sails framework. I imagine this is a pretty common requirement, so am surprised that I haven't found an npm module to do this, but having looked for quite a long time, I've found nothing. express.io does this but in reverse - it routes HTTP requests to socket.io handlers.

To clarify, I'd like to use my existing express app built in the usual way...

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

And then to link in socket.io so that the express route / can be executed on the client either with an HTTP call GET / or using socket.io with something like:

socket.emit('GET', '/', function(response) {
  // do something with the response
});

Ideally it'd also share sessions/authentication between express and socket.io (which I see from other posts on Stack Overflow is possible).

I could code this myself, but I can't believe there isn't a ready-made solution or npm module that already does this!

Upvotes: 1

Views: 759

Answers (1)

AesopWaits
AesopWaits

Reputation: 21

If I understand the question correctly you want to be able to access the same business logic server-side either via a socket event or a REST endpoint. This is entirely feasible if you have proper separation of concerns server-side. For example:

Assume you have an array of objects that was pulled from a data store server-side:

DataAccess.js:

function DataAccessor(){}

DataAccessor.prototype.getObjects = function(){
  var myObjects = new Array();
  return myObjects;
}


app.js //Routing for the REST endpoint and socket handling

app.get('/objects', function(req, res){
  res.send(new DataAccessor().getObjects());
});

var io = require('socket.io').listen(server);
io.sockets.on('connection', function (newSocket){
     newSocket.on('objects',function(){
      socket.emit('objectsSent',new DataAccessor().getObjects());
    });
});

In the above example, the client can call the REST endpoint via a GET request to "/objects" to retrieve the JSON collection. Firing a client-side socket event called 'objects' via socket.emit would also result in the server sending the same collection as a response message.

As an example client, these two segments would act similarly:

REST:
$.get("/objects",function(objectCollection){console.log(objectCollection);});

Sockets:
socket.on('objectsSent',function(objectCollection){console.log(objectCollection);});
socket.emit('objects');

Upvotes: 0

Related Questions