socket.io-router-middleware

1.1.2 • Public • Published

socket.io-router-middleware

Codeship Status for vojtaklos/socket.io-router-middleware

Easy to use router for sockets with methods (categories) for better code organization. Only works with Socket.io v2 because it relies on socket.use() method.

This library uses (route-parser)[https://www.npmjs.com/package/route-parser] for parsing the route paths. For info about how to write your paths please take a look at their docs.

Install

npm install --save socket.io-router-middleware

Usage

Example usage with Express server

Server

const app = require('express')()
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
 
// Require the router
const IORouter = new require('socket.io-router-middleware');
 
// Instantiate the router
const iorouter = new IORouter();
 
// Add router paths
iorouter.on('/api/:param?sort=:sort', (socket, ctx, next) => {
  ctx.response = {hello: 'from server'}
 
  socket.emit('response', ctx);
 
  // Don't forget to call next() at the end to enable passing to other middlewares
  next();
});
 
// On client connection attach the router
io.on('connection', function (socket) {
  socket.use((packet, next) => {
    // Call router.attach() with the client socket as the first parameter
    iorouter.attach(socket, packet, next)
  });
});
 
http.listen(port, function(){
  console.log('listening on *:' + port);
});

In the callback function of the route you have to send and event back and also call next() to let the flow continue to other middlewares. The name of the event is up to you but you have to listen for it on the frontend to actually get something back from the server. I usually use response as the event name. Also you dont need to send the response event with the ctx object but anything you want BUT the ctx object contains useful information like the original request object and matching route. The structure of the ctx object by default is as follows:

const ctx = {
    request: {
        method: 'on',
        params: {
            ...routeParams
        },
        route: '/matching/route?paramName=paramValue',
        ...anyOtherDataYouSend
    },
    response: {} // empty response object
}

You can fill the response object with the data in the callback function like this: ctx.response = {hello: 'world'}. And you can also add other properties. I usually stick to single response object for all the data but you can send whatever you want like errors for example. If there is an error you want to send though I would go with invoking it by executing the next funtion with an error instance like next(new Error('error content')). Which will let the socket.io client handle the error rather than you having to handle it yourself.

Client

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script>
    // connect to socket server
    const socket = io();
 
    // emit an event to your route path
    socket.emit('/api/test?sort=asc', {
        // payload is not required but can be used to send data
        payload: {
            hello: 'from client'
        }
    });
 
    // listen for response from server
    socket.on('response', ({request, response}) => {
        ...
    });
</script>

You can send anything you want in the socket.emit payload and it will be available to the server but some keys in the object are reserved:

  • method: Should be used to call a specific method set in allowedMethods parameter on the server. (If using the on method it can be left blank)
  • params: Is filled by the router and contains parameters defined in the route config
  • route: Contains the currently matched route

Parameters

allowedMethods

Specify methods (categories) of the router. This serves as an organizing tool only. It doesn't have any other effect. The default method that is ALWAYS generated is on. Specifying any routes here will create shorthand methods for calling them. For example

const router = new Router(['get', 'post']);
 
router.post('/api/create', (socket, ctx, next) => {...})
router.get('/api/read', (socket, ctx, next) => {...})
router.on('/api/update', (socket, ctx, next) => {...})

If left blank only the on shorthand will be generated

Methods

.attach(socket, packet, next)

Attches a router to the socket.

io.on('connection', function (socket) {
  socket.use((packet, next) => {
    router.attach(socket, packet, next)
  });
});

.route(method, route, callbackFn)

Universal function that is used by shorthand methods created with allowedMethods. !!! This function does not create the methods (categories) so passing a method that has not been defined in allowedMethods will result in an error

router.route('on', '/api/send', (socket, ctx, next) => {...})

.on(route, callbackFn)

A shorthand for router.route('on', '/route/path', (socket, ctx, next) => {}) aka the default route that is always available

Package Sidebar

Install

npm i socket.io-router-middleware

Weekly Downloads

1

Version

1.1.2

License

MIT

Unpacked Size

14.2 kB

Total Files

7

Last publish

Collaborators

  • vojtechklos