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

rpc-websocketserver

v2.0.0

Published

Simple rpc websocket server, wrapping the very popular 'ws' library. Register your RPCs with convenient decorators.

Downloads

7

Readme

rpc-websocketserver - A Node.js library

Version npm build Coverage Status

A simple and extensively documented typescript focused lib, to implement/prototype rpc websocket server applications with convenient decorators.

Wraps the popular ws lib.

Note: This is a backend focused library and therefore does not work in the browser.

Table of contents

Installing

With yarn (incl. peer dependencies)

yarn add rpc-websocketserver ws

With npm (incl. peer dependencies)

npm install rpc-websocketserver ws

Add experimental decorators and emit metadata to your tsconfig.json

// tsconfig.json
{
  "compilerOptions": {
    ...
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  },
  ...
}

Features, limitations and possible features to be added

This lib offers the following out of the box:

  • Extensive documentation for ease of development
  • Retains all functionality of the ws lib
  • RPC namespace creation
  • JSON RPC 2 conform message handler (incl. errors, responses and the like)
  • Simple message handler (super simplistic message handler)
  • Easily readable and maintainable registration of namespace methods with decorators
  • Convenience methods to interact with clients (e.g. broadcast messages to all clients). You are also able to override all ws listeners and convenience methods if you wish
  • Defined interfaces to implement your own custom message handlers

This lib does NOT offer the following:

  • Batch request handling
  • Runtime parameter typechecking on remote procedure call

Possible features to be added in the future:

  • Swagger like documentation generation with OpenRPC as model
  • Protected methods (require authentication before calling rpc)

Usage examples

Create namespaces for your rpc

import { WebSocketServer, register, param } from 'rpc-websocketserver';

// inherit from WebSocketServer
class NamespaceA extends WebSocketServer {
    constructor(messageHandler: MessageHandler, options: WebSocket.ServerOptions) {
       super(messageHandler, options);
    }
    
    @register()     // use the '@register' decorator to add function to the registered namespace methods
    sum(@param('a') a: number, @param('b') b: number) { // use the '@param' decorator to expose parameters
       return a + b;
    }

    @register('bar')     // optional: register a function with a specific name instead of the function name
    foo(@param('a') a: number, @param('b') b: number) { // use the '@param' decorator to expose parameters
       return a + b;
    }
}

// inherit from WebSocketServer
class NamespaceB extends WebSocketServer {
    constructor(messageHandler: MessageHandler, options: WebSocket.ServerOptions) {
       super(messageHandler, options);
    }
    
    @register()     // use the '@register' decorator to add function to the registered namespace methods
    substract(@param('a') a: number, @param('b') b: number) { // use the '@param' decorator to expose parameters
       return a - b;
    }

    @register('foo')     // optional: register a function with a specific name instead of the function name
    bar(@param('a') a: number, @param('b') b: number) { // use the '@param' decorator to expose parameters
       return a - b;
    }
}

Server

Set up your ws server similar like you would in the ws example and add your own namespaces

import express from 'express';
import http from 'http';
import url from 'url';

import { JSONRPC2MessageHandler } from 'rpc-websocketserver';
import { SimpleMessageHandler } from 'rpc-websocketserver';

const app = express();
const server = http.createServer(app);

// pass message handler instances and WebSocket.ServerOptions to the respective namespaces
const namespaceA = new NamespaceA(new SimpleMessageHandler(), { noServer: true });
// use different message handlers for different namespaces
const namespaceB = new NamespaceB(new JSONRPC2MessageHandler(), { noServer: true });


server.on('upgrade', function upgrade(request, socket, head) {
    const { pathname } = url.parse(request.url);

    if (pathname === '/a') {
        namespaceA.wss.handleUpgrade(request, socket, head, function done(ws: any) {
            namespaceA.wss.emit('connection', ws, request);
        });
    } else if (pathname === '/b') {
        namespaceB.wss.handleUpgrade(request, socket, head, function done(ws: any) {
            namespaceB.wss.emit('connection', ws, request);
        });
    } else {
        socket.destroy();
    }
});

server.listen(10001, '0.0.0.0', 1024, () => {
    console.log(`Listening for connections on 10001...`);
});

That's it for the server!

SimpleMessageHandler

Once you have started the server, you can start firing away messages to the implemented endpoints. Provided the example code above, we have two endpoints:

  • ws://localhost:10001/a (SimpleMessageHandler)
  • ws://localhost:10001/b (JSONRPC2MessageHandler)

Once you have connected to the endpoint with the SimpleMessageHandler you have to adhere to the defined message format:

  • Incoming messages must be of type string or Buffer
  • After reading the string or Buffer, the RPC must be an object
  • The object must have the "method" field with a value of type string
  • The object can have the "params" key. It may also be omitted.
  • If provided, the "params" field must either be of type object (named parameters), or of type array (positional parameters)

Valid remote procedure calls for the SimpleMessageHandler

Positional parameters:

{
  "method": "sum",
  "params": [1, 2]
}

Named parameters:

{
  "method": "sum",
  "params": { "b": 2, "a": 1 }
}

Omitted parameters:

{
  "method": "doSomething"
}

Overriding provided WebSocketServer functionality

Currently, the WebSocketServer offers the following functionality out of the box:

  • Public function to retrieve all registered methods for the specific namespace
  • Public function to broadcast a message to all clients of this namespace
  • Protected function to send a message to a specific client
  • Protected function to set ws listeners once a connection was established
  • Protected function to handle received messages

All protected functions can be overridden for your specific namespaces. You are encouraged to override the 'onConnection' handler with handlers for the possible ws events (e. g. error) like so:

import WebSocket from 'ws';
import { MessageHandler, WebSocketServer, register, param } from 'rpc-websocketserver';

// inherit from WebSocketServer
class NamespaceA extends WebSocketServer {
    constructor(messageHandler: MessageHandler, options: WebSocket.ServerOptions) {
       super(messageHandler, options);
    }

    @register()
    sum(@param('a') a: number, @param('b') b: number) {
       return a + b;
    }

    // overriding the onConnection handler to add more event listeners once a connection is established
    protected _onConnection(ws: WebSocket): void {
        super._onConnection(ws);
        ws.addListener('error', (err: Error) => console.log(err));
    }
}

This inheritance based approach should facilitate your own implementation for custom error/message handling, logging, clean up functionality on close events and so on.

Changelog

Changelog

Contributing

Feel free to give feedback through issues or open pull requests with improvements.

License

MIT