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

essocket

v0.0.6

Published

Library for easy use of socket.io with MVC pattern

Downloads

2

Readme

easy-socket

onix

Library for easy use of socket.io with MVC pattern

Install

npm i essocket

API

Examples

Require module

// ./main.js
const io = require('socket.io');
const http = require('http');
const { Socket } = require('essocket');

Socket.init(io(http.createServer()), options);

| Param | Type | Description | Required | | ------------------- | ------------------- | --------------------------------------- | -------- | | Server | Socket server | Socket io instance | true | | options | Object | | false | | options.interceptor | Function | Transform the exception thrown from a function | false | | options.auth | Function | Middleware for authenticate client | false |

gateway

create gateway

// ./modules/test/test.gateway.js

const { Gateway } = require('essocket');

const TestGateway = new Gateway('test');

TestGateway.addListener('hello', (ctx, data) => { return 'Hello world!' });

use gateway

// ./main.js
const io = require('socket.io');
const http = require('http');
const { Socket } = require('essocket');

const TestGateway = require('./modules/test/test.gateway.js');

Socket.use(TestGateway);

Socket.init(io(http.createServer()), options);

emit event

// client.html
  socket.on('connect', () => {
    scoket.emit('test/hello', {}, ({ data, error }) => {
      if(error) {
        console.error(error)
      }
  
      console.log(data) // Hello world
    });
  }

listeners

create listeners

// ./modules/test/test.listeners.js

class TestListeners {
    myFirstListener(ctx, data) {
        console.log('socket.io server :>> ', ctx.server);
        console.log('client socket :>> ', ctx.socket);
      
        return 'Hello world!';
    }
}

module.exports = new TestListeners();

use listeners

// ./modules/test/test.gateway.js

const { Gateway } = require('essocket');
const TestListeners = require('./test.listeners');

const TestGateway = new Gateway('test');

TestGateway.addListener('hello', TestListeners.myFirstListener);

emiteds

create emiteds

// ./modules/test/test.emiteds.js

const { Emiteds } = require('essocket');

class TestEmiteds extends Emiteds {
    sendMyFirstEvent(ctx, message) {
        this.emit(ctx.socket, 'test-event', {
            data: message,
        });
    }
}

module.exports = new TestEmiteds('test');

use emiteds

// ./modules/test/test.listeners.js

const TestEmiteds = require('./test.emiteds');

class TestListeners {
    myFirstListener(ctx, data) {
        TestEmiteds.sendMyFirstEvent(ctx, 'Hi client!')
      
        return 'Hello world!';
    }
}

module.exports = new TestListeners();

listen emit

// client.html
  socket.on('connect', () => {
    socket.on('test/test-event', ({ data }) => {
      console.log(data) // Hi client!
    });
    
    scoket.emit('test/hello', {}, ({ data, error }) => {
      if(error) {
        console.error(error)
      }
  
      console.log(data) // Hello world
    });
  }

validation

create validation schema

// ./modules/test/test.validations.js

const { Validator } = require('essocket');

const schema = Validator.createSchema(Joi => {
    return {
        username: Joi.string().alphanum().min(3).max(30).required(),
        birth_year: Joi.number().integer().min(1900).max(2013),
    };
});

module.exports = {
    myFirstValidationSchema: schema,
};

use validation

// ./modules/test/test.gateway.js

const { Gateway } = require('essocket');
const TestListeners = require('./test.listeners');
const { myFirstValidationSchema } = require('./test.validations');

const TestGateway = new Gateway('test');

TestGateway.addListener('hello', TestListeners.myFirstListener)
           .validate(myFirstValidationSchema);
           

catch error in client

// client.html
  socket.on('connect', () => {
    scoket.emit('test/hello', {}, ({ data, error }) => {
      console.error(error) // { message: "Error message", statusCode: 400, name: "Bad Request" }
    });
  }

auth

set auth middleware and protect gateway

// ./main.js
// example with jwt

const io = require('socket.io');
const http = require('http');
const { Socket } = require('essocket');
const jwt = require('jwt');

const TestGateway = require('./modules/test/test.gateway.js');

Socket.use(TestGateway, { protected:true });

Socket.init(io(http.createServer()), {
    auth: socket => {
        const { token } = socket.handshake.auth;

        if (token) {
            try {
                const payload = jwt.verify(
                    token.split('Bearer ')[1],
                    'jwt secret key',
                );

                return { user: payload };
            } catch (error) {
                return { error };
            }
        }

        return { error: new Error('Access token not exist!') };
    },
});

on client

// client.html
    const socket = io('http://localhost:3000', {
       auth: {
               token: `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbiI6eyJ1c2VyX2lkIjoyNSwiZnVsbF9uYW1lIjoiTGlvbHlrIn0sImlhdCI6MTYyNzU0NTE1NH0.thTscgsv0Rr8MZlNugVzaA7Dd7w_UZswXhgiyyRXWbs`,
              }
            });

  socket.on('connect', () => {
    socket.on('common/on-auth-error', ({error}) => {
        console.log('on-auth-error :>> ');
        console.log(error);
     });
                
    socket.emit('test/hello', {}, ({ data, error }) => {
      console.error(error) // { message: "Error message", statusCode: 400, name: "Bad Request" }
    });
  }

interceptor

create custom interceptor

// ./main.js

const io = require('socket.io');
const http = require('http');
const { Socket, exceptions: { Exception } } = require('essocket');

const TestGateway = require('./modules/test/test.gateway.js');

Socket.use(TestGateway);

Socket.init(io(http.createServer()), {
    interceptor: (error, cb) => {
      if (!error.statusCode || error.statusCode === 500) {
          console.log(error);

          return cb({
              error: new Exception(error.message, 500),
          });
      }

      cb({ error });
  }
});

upload files

add upload listener

// ./modules/test/test.listeners.js

class TestListeners {
    myFirstListener(ctx, data) {
        console.log('socket.io server :>> ', ctx.server);
        console.log('client socket :>> ', ctx.socket);
      
        return 'Hello world!';
    }
    
    uploadImage(ctx, file) {
      console.log('file :>> ', file);
      }
}

module.exports = new TestListeners();

use upload listener

// ./modules/test/test.gateway.js

const { Gateway } = require('essocket');
const TestListeners = require('./test.listeners');

const TestGateway = new Gateway('test');

TestGateway.addListener('hello', TestListeners.myFirstListener);

TestGateway.addFileListener('image', TestRoomListeners.uploadImage);

serve client uploader

// ./main.js

const io = require('socket.io');
const http = require('http');
const { Socket, Uploader } = require('essocket');

const TestGateway = require('./modules/test/test.gateway.js');

const server = http.createServer();

// add route /siofu/client.js on server
Uploader.serveClient(server)

Socket.use(TestGateway);

Socket.init(io(server));

on client

// client.html
  <form id="form">
      <input type="file" name="file" />
      <button type="submit">Sent</button>
  </form>
 <script src="http://localhost:3000/siofu/client.js">
      const socket = io('http://localhost:3000');
      
      const uploader = new SocketIOFileUpload(socket);
      
      const setImageTypeListener = function (event) {
        event.file.meta.type = 'image';
      };

      socket.on('connect', () => {
        form.addEventListener('submit', e => {
          event.preventDefault();
          
          uploader.addEventListener('start', setImageTypeListener);
          
          uploader.submitFiles(e.target.file.files);
          
          uploader.removeEventListener('start', setImageTypeListener);
        });
        
        socket.on('common/on-auth-error', ({error}) => {
            console.log('on-auth-error :>> ');
            console.log(error);
         });

        socket.emit('test/hello', {}, ({ data, error }) => {
          console.error(error) // { message: "Error message", statusCode: 400, name: "Bad Request" }
        });
      }
</script>