npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

socket.io-router-middleware

v1.1.2

Published

Easy to use router for sockets with methods (categories) for better code organization.

Downloads

25

Readme

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