Skip to content

An alternative API for writing socket.io event handlers

License

Notifications You must be signed in to change notification settings

assisrafael/socket.io-routes

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

socket.io-routes Build Status Coverage Status

NPM

An alternative API for writing socket.io event handlers

How to use

const io = require('socket.io');
const routes = require('socket.io-routes');
//...
io.use(routes);

io.on('connection', function(s) {
  s.route('event')
    .process(function(data) {
      s.emit('success', 'some data');
    });
});

Instead of sending manually a message, you can return a value to the callback of the event (if available):

s.route('event')
  .process(function(data) {
    doSomething().then(() => {
      return doSomething();
    });
  });

You can add authentication (assumes an authentication middleware like the following):

io.use(function authenticateMiddleware(s, next) {
  if (!s.auth) {
    s.auth = {};
  }

  if (s.handshake.query.token === 'secret') {
    s.auth.isAuthenticated = true;
  }

  next();
});
//...
s.route('event')
  .auth({
    isAuthenticated: true
  })
  .process(function(data) {
    return doSomething();
  });

And you can also validate data using node-validator:

s.route('event')
  .validate({
    email: {
      isEmail: {},
      isLowercase: true
  })
  .process(function(data) {
    return doSomething();
  });

About

An alternative API for writing socket.io event handlers

Resources

License

Stars

Watchers

Forks

Packages

No packages published