🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

socket.io-as-promised

Package Overview
Dependencies
Maintainers
2
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

socket.io-as-promised

Socket.IO middleware for supporting returning promises from handlers

latest
Source
npmnpm
Version
4.0.0
Version published
Weekly downloads
66
34.69%
Maintainers
2
Weekly downloads
 
Created
Source

socket.io-as-promised

Build Status npm package Coverage Status

Socket.IO middleware for supporting returning promises from handlers

Introduction

Allows you to more easily respond to your user's events by employing promises instead of callbacks. Supports Node >= 16.

It also helps with error handling, which is important since Socket.IO does not serialize Error objects.

Install

$ npm install --save socket.io-as-promised

Usage

// server.js
import { Server } from 'socket.io';
import asPromised from 'socket.io-as-promised';

const io = new Server(5000);

// on the main '/' namespare
io.use(socketAsPromised());

// on a custom namespace
io.of('/foo').use(socketAsPromised());

io.on('connection', socket => {
  // Client will get a response with the string 'returned a promise'
  socket.on('returns promise', () => Promise.resolve('returned a promise'));

  // Client will get a response with the string 'returned from async function'
  socket.on('returns from async', async () => 'returned from async function');

  // Handles errors
  socket.on('throws exception', () => Promise.reject({ error: 'thrown exception' }));
  socket.on('throws from async', async () => { throw { error: 'thrown exception' }; });

  // Error objects get turned into '{}' objects by socket io, so they need serializing
  // use the handleError option documented in the API to handle this case
  socket.on('throws error exception', () => Promise.reject(new Error('thrown exception')));
});
// client.js
const io = require('socket.io-client');
const client = io.connect('http://0.0.0.0:5000');

client.emit('returns promise', (err, res) => console.log(res)); // 'returned a promise'
client.emit('returns from async', (err, res) => console.log(res)); // 'returned from async'

client.emit('throws exception', err => console.log(err)); // { error: 'thrown exception' }
client.emit('throws from async', err => console.log(err)); // { error: 'thrown exception' }

client.emit('throws error exception', err => console.log(err)); // {}

API

socketAsPromised({ handleError } = {})

Type: function

Returns Socket.IO middleware. Monkeypatches socket.on to wrap the handler function and support returned promises

handleError(err, event)

Type: function, default: null

Optional argument, helps in case you want to ignore certain errors, or serialize other errors.

io.use(socketAsPromised({
  handleError(err, event) {
    return Promise.reject({ name: err.name, message: err.message });

    // or:
    throw { name: err.name, message: err.message };

    // more fancy usage, filter out certain errors, return a
    // generic error instead useful in case of errors like database
    // connectivity that you don't want to reach the end user
    const genericError = { name: 'GenericError', message: 'Something went wrong' };

    if (isKnownError(err.name)) {
      return Promise.reject({ name: err.name, message: err.message });
    }
    return Promise.reject(genericError);
  }
}))

Tests

npm test

You can customize the port under which the test server runs (by default 8090):

TEST_PORT=4444 npm test

License

See the LICENSE file for license rights and limitations (MIT).

Keywords

socket.io

FAQs

Package last updated on 01 May 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts