{"id":16222333,"url":"https://github.com/johnbra/rpc-websocketserver","last_synced_at":"2025-10-29T03:31:22.896Z","repository":{"id":56544298,"uuid":"276118532","full_name":"JohnBra/rpc-websocketserver","owner":"JohnBra","description":"Simple rpc-websocketserver wrapping the very popular 'ws' library. Register your RPCs with convenient decorators","archived":false,"fork":false,"pushed_at":"2020-11-01T16:05:19.000Z","size":483,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-12-21T15:46:45.372Z","etag":null,"topics":["json-rpc-server","json-rpc2","rpc","rpc-server","websocket-server","ws"],"latest_commit_sha":null,"homepage":"https://github.com/JohnBra/rpc-websocketserver","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/JohnBra.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-06-30T14:12:48.000Z","updated_at":"2023-07-27T05:48:51.000Z","dependencies_parsed_at":"2022-08-15T20:40:32.739Z","dependency_job_id":null,"html_url":"https://github.com/JohnBra/rpc-websocketserver","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnBra%2Frpc-websocketserver","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnBra%2Frpc-websocketserver/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnBra%2Frpc-websocketserver/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnBra%2Frpc-websocketserver/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/JohnBra","download_url":"https://codeload.github.com/JohnBra/rpc-websocketserver/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":238763434,"owners_count":19526587,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["json-rpc-server","json-rpc2","rpc","rpc-server","websocket-server","ws"],"created_at":"2024-10-10T12:12:55.503Z","updated_at":"2025-10-29T03:31:22.468Z","avatar_url":"https://github.com/JohnBra.png","language":"TypeScript","readme":"# rpc-websocketserver - A Node.js library\n[![Version npm](https://img.shields.io/npm/v/rpc-websocketserver.svg?logo=npm)](https://www.npmjs.com/package/rpc-websocketserver)\n![build](https://github.com/JohnBra/rpc-websocketserver/workflows/build/badge.svg)\n[![Coverage Status](https://coveralls.io/repos/github/JohnBra/rpc-websocketserver/badge.svg?branch=master)](https://coveralls.io/github/JohnBra/rpc-websocketserver?branch=master)\n\nA simple and extensively documented typescript focused lib, to implement/prototype rpc websocket server applications with convenient decorators.\n\nWraps the popular [ws](https://github.com/websockets/ws) lib.\n\n**Note**: This is a backend focused library and therefore does not work in the browser.\n\n## Table of contents\n- [Installing](#installing)\n- [Features, limitations and possible features to be added](#features-limitations-and-possible-features-to-be-added)\n    - [Features](#this-lib-offers-the-following-out-of-the-box)\n    - [Limitations](#this-lib-does-not-offer-the-following)\n    - [Possible features](#possible-features-to-be-added-in-the-future)\n- [Usage examples](#usage-examples)\n    - [Create namespaces for your rpc](#create-namespaces-for-your-rpc)\n    - [Server](#server)\n    - [SimpleMessageHandler](#simplemessagehandler)\n    - [Overriding provided WebSocketServer functionality](#overriding-provided-websocketserver-functionality)\n- [Changelog](#changelog)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Installing\nWith yarn (incl. peer dependencies)\n```bash\nyarn add rpc-websocketserver ws\n```\nWith npm (incl. peer dependencies)\n```\nnpm install rpc-websocketserver ws\n```\nAdd experimental decorators and emit metadata to your `tsconfig.json`\n```json\n// tsconfig.json\n{\n  \"compilerOptions\": {\n    ...\n    \"experimentalDecorators\": true,\n    \"emitDecoratorMetadata\": true\n  },\n  ...\n}\n```\n## Features, limitations and possible features to be added\n### This lib offers the following out of the box:\n- Extensive documentation for ease of development\n- Retains all functionality of the [ws](https://github.com/websockets/ws) lib\n- RPC namespace creation\n- [JSON RPC 2](https://www.jsonrpc.org/specification) conform message handler (incl. errors, responses and the like)\n- Simple message handler (super simplistic message handler)\n- Easily readable and maintainable registration of namespace methods with decorators\n- 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*\n- Defined interfaces to implement your own custom message handlers\n\n### This lib does **NOT** offer the following:\n- Batch request handling\n- Runtime parameter typechecking on remote procedure call\n\n### Possible features to be added in the future:\n- [Swagger](https://swagger.io/) like documentation generation with [OpenRPC](https://open-rpc.org/) as model\n- Protected methods (require authentication before calling rpc)\n\n## Usage examples\n\n### Create namespaces for your rpc\n```typescript\nimport { WebSocketServer, register, param } from 'rpc-websocketserver';\n\n// inherit from WebSocketServer\nclass NamespaceA extends WebSocketServer {\n    constructor(messageHandler: MessageHandler, options: WebSocket.ServerOptions) {\n       super(messageHandler, options);\n    }\n    \n    @register()     // use the '@register' decorator to add function to the registered namespace methods\n    sum(@param('a') a: number, @param('b') b: number) { // use the '@param' decorator to expose parameters\n       return a + b;\n    }\n\n    @register('bar')     // optional: register a function with a specific name instead of the function name\n    foo(@param('a') a: number, @param('b') b: number) { // use the '@param' decorator to expose parameters\n       return a + b;\n    }\n}\n\n// inherit from WebSocketServer\nclass NamespaceB extends WebSocketServer {\n    constructor(messageHandler: MessageHandler, options: WebSocket.ServerOptions) {\n       super(messageHandler, options);\n    }\n    \n    @register()     // use the '@register' decorator to add function to the registered namespace methods\n    substract(@param('a') a: number, @param('b') b: number) { // use the '@param' decorator to expose parameters\n       return a - b;\n    }\n\n    @register('foo')     // optional: register a function with a specific name instead of the function name\n    bar(@param('a') a: number, @param('b') b: number) { // use the '@param' decorator to expose parameters\n       return a - b;\n    }\n}\n```\n\n### Server\nSet up your ws server similar like you would in the [ws example](https://github.com/websockets/ws/blob/master/README.md#multiple-servers-sharing-a-single-https-server) and add your own namespaces\n```typescript\nimport express from 'express';\nimport http from 'http';\nimport url from 'url';\n\nimport { JSONRPC2MessageHandler } from 'rpc-websocketserver';\nimport { SimpleMessageHandler } from 'rpc-websocketserver';\n\nconst app = express();\nconst server = http.createServer(app);\n\n// pass message handler instances and WebSocket.ServerOptions to the respective namespaces\nconst namespaceA = new NamespaceA(new SimpleMessageHandler(), { noServer: true });\n// use different message handlers for different namespaces\nconst namespaceB = new NamespaceB(new JSONRPC2MessageHandler(), { noServer: true });\n\n\nserver.on('upgrade', function upgrade(request, socket, head) {\n    const { pathname } = url.parse(request.url);\n\n    if (pathname === '/a') {\n        namespaceA.wss.handleUpgrade(request, socket, head, function done(ws: any) {\n            namespaceA.wss.emit('connection', ws, request);\n        });\n    } else if (pathname === '/b') {\n        namespaceB.wss.handleUpgrade(request, socket, head, function done(ws: any) {\n            namespaceB.wss.emit('connection', ws, request);\n        });\n    } else {\n        socket.destroy();\n    }\n});\n\nserver.listen(10001, '0.0.0.0', 1024, () =\u003e {\n    console.log(`Listening for connections on 10001...`);\n});\n```\n\nThat's it for the server!\n\n### SimpleMessageHandler\nOnce you have started the server, you can start firing away messages to the implemented endpoints. Provided the example code above, we have two endpoints:\n- ws://localhost:10001/a (SimpleMessageHandler)\n- ws://localhost:10001/b (JSONRPC2MessageHandler)\n\nOnce you have connected to the endpoint with the **SimpleMessageHandler** you have to adhere to the defined message format:\n- Incoming messages must be of type string or Buffer\n- After reading the string or Buffer, the RPC must be an object\n- The object must have the \"method\" field with a value of type string\n- The object can have the \"params\" key. It may also be omitted.\n- If provided, the \"params\" field must either be of type object (named parameters), or of type array (positional parameters)\n\nValid remote procedure calls for the SimpleMessageHandler\n\nPositional parameters:\n```json\n{\n  \"method\": \"sum\",\n  \"params\": [1, 2]\n}\n```\nNamed parameters:\n```json\n{\n  \"method\": \"sum\",\n  \"params\": { \"b\": 2, \"a\": 1 }\n}\n```\nOmitted parameters:\n```json\n{\n  \"method\": \"doSomething\"\n}\n```\n\n### Overriding provided WebSocketServer functionality\nCurrently, the [WebSocketServer](https://github.com/JohnBra/rpc-websocketserver/blob/master/src/lib/websocket-server.ts#L21) offers the following functionality out of the box:\n- **Public** function to **retrieve all registered methods** for the specific namespace\n- **Public** function to **broadcast a message** to all clients of this namespace\n- **Protected** function to **send a message** to a specific client\n- **Protected** function to **set ws listeners** once a connection was established\n- **Protected** function to **handle received messages**\n\nAll protected functions can be overridden for your specific namespaces. You are encouraged to override the 'onConnection' handler with handlers for the possible [ws events](https://github.com/websockets/ws/blob/master/doc/ws.md#event-close-1) (e. g. error) like so:\n```typescript\nimport WebSocket from 'ws';\nimport { MessageHandler, WebSocketServer, register, param } from 'rpc-websocketserver';\n\n// inherit from WebSocketServer\nclass NamespaceA extends WebSocketServer {\n    constructor(messageHandler: MessageHandler, options: WebSocket.ServerOptions) {\n       super(messageHandler, options);\n    }\n\n    @register()\n    sum(@param('a') a: number, @param('b') b: number) {\n       return a + b;\n    }\n\n    // overriding the onConnection handler to add more event listeners once a connection is established\n    protected _onConnection(ws: WebSocket): void {\n        super._onConnection(ws);\n        ws.addListener('error', (err: Error) =\u003e console.log(err));\n    }\n}\n```\n\nThis inheritance based approach should facilitate your own implementation for custom error/message handling, logging, clean up functionality on close events and so on.\n\n## Changelog\n[Changelog](https://github.com/JohnBra/rpc-websocketserver/blob/master/CHANGELOG.md)\n\n## Contributing\nFeel free to give feedback through issues or open pull requests with improvements.\n\n## License\n[MIT](https://github.com/JohnBra/rpc-websocketserver/blob/master/LICENSE)\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjohnbra%2Frpc-websocketserver","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjohnbra%2Frpc-websocketserver","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjohnbra%2Frpc-websocketserver/lists"}