# rpc2-websocket-client

> Fast JSON

Latest version **1.1.5** (published 2023-08-05) · MIT license · 0 weekly downloads

## Install

```sh
npm install rpc2-websocket-client
pnpm add rpc2-websocket-client
yarn add rpc2-websocket-client
bun add rpc2-websocket-client
```

## Health

**Score 30/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.1.5 |
| Published | 2023-08-05 |
| First published | 2023-08-05 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=6.0.0 |
| Dependencies | 3 |
| Unpacked size | 124.4 KB |
| Known vulnerabilities | 0 (+1 in 1 direct dependencies) |
| Install scripts | no |
| Author | Artur Kurowski |
| Maintainers | g201568820 |
| Keywords | websocket, client, typescript, json rpc, 2.0, fast |

## Links

- npm: https://www.npmjs.com/package/rpc2-websocket-client
- npm.io page: https://npm.io/package/rpc2-websocket-client

## Dependencies (3)

- [ws](https://npm.io/package/ws.md) ^7.1.2
- [uuid](https://npm.io/package/uuid.md) ^3.3.3
- [isomorphic-ws](https://npm.io/package/isomorphic-ws.md) ^4.0.1

## Alternatives

- [@opentelemetry/exporter-zipkin](https://npm.io/package/@opentelemetry/exporter-zipkin.md) — 14.8M weekly downloads
- [pusher-js](https://npm.io/package/pusher-js.md) — 2.0M weekly downloads
- [browserify](https://npm.io/package/browserify.md) — 1.7M weekly downloads
- [sqs-consumer](https://npm.io/package/sqs-consumer.md) — 1.7M weekly downloads
- [@sanity/eventsource](https://npm.io/package/@sanity/eventsource.md) — 930.8K weekly downloads

## Recent versions

- 1.1.5 (latest) — 2023-08-05
- 1.1.4 — 2023-08-05

## README

<p align="center">
    <a href="https://github.com/radarsu/rpc-websocket-client/" target="blank"><img src="https://raw.githubusercontent.com/radarsu/rpc-websocket-client/master/assets/logo.png" alt="rpc-websocket-client" /></a><br/>
    <strong>Fast JSON RPC 2.0 written in TypeScript.</strong>
</p>

<p align="center">
<a href="https://github.com/Microsoft/TypeScript" target="blank">TypeScript</a> <a href="https://www.jsonrpc.org/specification" target="_blank" alt="JSON RPC 2.0">JSON RPC 2.0</a> WebSocket implementation with async-await Promises.<br/>
</p>

<p align="center">
	<a href="https://www.npmjs.com/package/rpc-websocket-client" target="_blank" alt="npm rpc-websocket-client"><img src="https://img.shields.io/npm/v/rpc-websocket-client.svg" alt="npm" /></a>
	<img src="https://img.shields.io/github/license/radarsu/rpc-websocket-client.svg" />
	<img src="https://img.shields.io/github/stars/radarsu/rpc-websocket-client.svg" />
	<a href="https://twitter.com/radarsujs"><img src="https://img.shields.io/twitter/url/https/github.com/radarsu/rpc-websocket-client.svg?style=social" /></a>
</p>

[!["Buy Me A Coffee"](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/radarsu)
## Description

I really lacked typescript support or type definitions of <a href="https://github.com/elpheria/rpc-websockets" target="_blank" alt="rpc-websockets">rpc-websockets</a>. I kept everything as simple as possible for <strong>best performance</strong> and in principle <strong>stay close to the metal</strong>. Under the hood id-generation for requests is done using <a href="https://github.com/kelektiv/node-uuid" target="_blank" alt="uuid">uuid/v1</a> to provide id uniqueness as an additional feature.

## Installation
Using npm:
```sh
npm i rpc2-websocket-client
```
Using CDN （on browsers）
```html
<script src="https://cdn.jsdelivr.net/npm/rpc2-websocket-client/dist/rpc-websocket-client.umd.full.js"></script>
```

## Features

- <strong>TypeScript</strong> with documentation in comments.
- <strong>Unique RPC identifiers</strong> by <a href="https://github.com/kelektiv/node-uuid" target="_blank" alt="uuid">uuid/v1</a>.
- <strong>Lightweight</strong>. Allows you to call `noRpc()` method to prevent sending `jsonrpc: '2.0'` overhead from all messages if you'd like to ignore the <a href="https://www.jsonrpc.org/specification" target="_blank" alt="JSON RPC 2.0">JSON RPC 2.0</a> standard for better performance.
- Option to <strong>connect RpcWebSocketClient with already existing WebSocket</strong> with `changeSocket()` and `listenMessages()` methods. Useful if you use <strong>REST</strong> or <strong>GraphQL implementation</strong> from another library and want to handle <a href="https://www.jsonrpc.org/specification" target="_blank" alt="JSON RPC 2.0">JSON RPC 2.0</a> when communicating from server to client (that was my use case to develop this package).

## Basic Usage
```ts
// vite 使用'rpc-websocket-client.umd.full'，解决require is not defined问题
// import {RpcWebSocketClient} from 'rpc2-websocket-client/dist/rpc-websocket-client.umd.full';
// vite.config.ts 增加以下配置
// export default {
//     optimizeDeps: {
//         include: ['rpc2-websocket-client/dist/rpc-websocket-client.umd.full']
//     }
// };
import { RpcWebSocketClient } from 'rpc2-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
```ts
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();
})();
```

---
_Source: https://npm.io/package/rpc2-websocket-client · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
