Giter VIP home page Giter VIP logo

radarsu / rpc-websocket-client Goto Github PK

View Code? Open in Web Editor NEW
34.0 9.0 9.0 2.23 MB

Fast and simple JSON-RPC 2.0 WebSocket Client implementation in TypeScript. Allows bi-directional communication with async await Promises ๐Ÿผ

Home Page: https://radarsu.radrat.pl/rpc-websocket-client/

License: MIT License

TypeScript 98.23% JavaScript 1.77%
rpc-client websocket-client websocket fast rpc jsonrpc2 bidirectional communication rpc-websockets fast-json-stringify

rpc-websocket-client's Introduction

rpc-websocket-client
Fast JSON RPC 2.0 written in TypeScript.

TypeScript JSON RPC 2.0 WebSocket implementation with async-await Promises.

npm

"Buy Me A Coffee"

Description

I really lacked typescript support or type definitions of rpc-websockets. I kept everything as simple as possible for best performance and in principle stay close to the metal. Under the hood id-generation for requests is done using uuid/v1 to provide id uniqueness as an additional feature.

Installation

npm i rpc-websocket-client

Features

  • TypeScript with documentation in comments.
  • Unique RPC identifiers by uuid/v1.
  • Lightweight. Allows you to call noRpc() method to prevent sending jsonrpc: '2.0' overhead from all messages if you'd like to ignore the JSON RPC 2.0 standard for better performance.
  • Option to connect RpcWebSocketClient with already existing WebSocket with changeSocket() and listenMessages() methods. Useful if you use REST or GraphQL implementation from another library and want to handle JSON RPC 2.0 when communicating from server to client (that was my use case to develop this package).

Basic Usage

import { RpcWebSocketClient } from 'rpc-websocket-client';

(async () => {

    const rpc = new RpcWebSocketClient();
    await rpc.connect(`ws://localhost:4000/`);
    // Connection is established now.

    // Let's hope there will be no error or it will be catched in some wrapper.
    await rpc.call(`auth.login`, [`rpcMaster`, `mySecretPassword`]);

    // Now lets be pesimistic.
    const res = await rpc.call(`auth.login`, [`rpcMaster`, `mySecretPassword`]).then(() => {
        // Woohoo, user logged!
    }).catch((err) => {

        // Err is typeof RpcError (code: number, message: string, data?: any).
        await rpc.call(`auth.signup`, {
            login: `rpcMaster`,
            password: `mySecretPassword`,
        });

        return false;
    });

    // If catch wrapper returned false, let's not continue.
    if (res === false) {
        return;
    }

    rpc.notify(`btw.iHateYou`, [`over and out`]);

    // Close the connection by using native ws.close().
    rpc.ws.close();

})();

Advanced Usage

import { RpcWebSocketClient } from 'rpc-websocket-client';

(async () => {
    // lets say you use WebSocket implementation for GraphQL Client -> Server communication
    // e.g. Apollo, and it's already connected
    // but you want to handle some of the Server -> Client communication with RPC

    const ws = (apollo as any).client.wsImpl;
    const rpc = new RpcWebSocketClient();

    rpc.onRequest.push((data) => {       // data is typeof RpcRequest
        // controller-like stuff
    });

    rpc.onNotification.push((data) => {  // data is typeof RpcNotification
        // notification handling
    });

    // here goes magic for listening to already-connected socket
    rpc.changeSocket(ws);
    rpc.listenMessages();
})();

rpc-websocket-client's People

Contributors

dependabot[bot] avatar radarsu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rpc-websocket-client's Issues

JSON-RPC response with null result raises error

When the websocket server returns a JSON-RPC successful response which has null result, rpc-websocket-client (version 1.1.3) throws TypeError as below:

Response JSON-RPC Message

{jsonrpc: "2.0", id: "29087a00-ebff-11e9-aefb-7b66852aac88", result: null}

Error

home.js:341 Uncaught TypeError: Cannot read property 'code' of null
    at RpcWebSocketClient.push../node_modules/rpc-websocket-client/dist/rpc-websocket-client.es5.js.RpcWebSocketClient.isRpcError (home.js:341)
    at Object._this.idAwaiter.<computed> (home.js:186)
    at WebSocket.ws.onmessage (home.js:146)

(home.js is my Vue component script)

When a response message has a result value other than null, this error does not happen.

It seems that the response message is handled as a sucessful response, but this line is not properly processed.
https://github.com/radarsu/rpc-websocket-client/blob/master/src/rpc-websocket-client.ts#L176

How about use `isomorphic-ws` for nodejs client

  • I'm submitting a ...
  • feature request
  • Summary
    Propose to use isomorphic-ws instead of native WebSocket.

  • Error trace

ReferenceError: WebSocket is not defined
    at RpcWebSocketClient.connect (foo/bar/node_modules/rpc-websocket-client/src/lib/index.ts:102:23)

How to receive a notification message in TypeScript

Hi,
First of all thank you for making such a nice library.

I write code in TypeScript, and noticed that RpcWebSocketClient.onNotification() method is private.
https://github.com/radarsu/rpc-websocket-client/blob/master/src/rpc-websocket-client.ts#L79

So how can I receive a JSON-RPC notification message from WebSocket server?

In order to make a chat application, I need to handle notification messages from server other than rpc request's responses.

Build Error TS2304: Cannot find name 'RpcWebSocketConfig'

  • I'm submitting a ...
  • bug report
  • Summary
    env:
    node/11.6.0

reproduction:

  • git clone blahblah
  • yarn
  • yarn build

=>

Build error:

src/lib/index.ts:81:21 - error TS2304: Cannot find name 'RpcWebSocketConfig'.

81     private config: RpcWebSocketConfig = {
                       ~~~~~~~~~~~~~~~~~~

src/lib/index.ts:139:13 - error TS2322: Type '(ev: MessageEvent) => any' is not assignable to type 'RpcEventFunction'.
  Types of parameters 'ev' and 'e' are incompatible.
    Type 'Event' is missing the following properties from type 'MessageEvent': data, lastEventId, origin, ports, source

139             previousOnMessage = this.ws.onmessage.bind(this.ws);
                ~~~~~~~~~~~~~~~~~

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.