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-as-promised

v4.0.0

Published

Socket.IO middleware for supporting returning promises from handlers

Downloads

143

Readme

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).