0.0.3 • Published 7 months ago

@tioniq/json-rpc v0.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

Json-RPC 2.0 Implementation

npm version npm bundle size tree-shakeable license

Easy to use and lightweight JSON-RPC 2.0 implementation for Node.js and browser. The same implementation can be used on both sides.

Installation

npm install @tioniq/json-rpc

Usage

Server example

import { Peer } from '@tioniq/json-rpc';
import { ChannelMinimal } from './channel';
import { EventDispatcher } from '@tioniq/eventiq';

const socket = /* Your socket implementation */ null;

const messageDispatcher = new EventDispatcher<string>();

socket.on('message', (message: string) => {
  messageDispatcher.dispatch(message);
});

const channel: ChannelMinimal<string> = {
  onMessage: messageDispatcher,

  send(message: string) {
    return socket.send(message);
  }
};
const rpcPeer = new Peer(channel);

// Register a method
rpcPeer.setRequestHandler('sum', (a: number, b: number) => a + b);

Client example

import { Peer } from '@tioniq/json-rpc';
import { ChannelMinimal } from './channel';
import { EventDispatcher } from '@tioniq/eventiq';

const socket = /* Your socket implementation */ null;

const messageDispatcher = new EventDispatcher<string>();

socket.on('message', (message: string) => {
  messageDispatcher.dispatch(message);
});

const channel: ChannelMinimal<string> = {
  onMessage: messageDispatcher,

  send(message: string) {
    return socket.send(message);
  }
};
const rpcPeer = new Peer(channel);

// Send request
const result = await rpcPeer.sendRequest('sum', [1, 2]);
console.log(result); // 3
0.0.3

7 months ago

0.0.2

7 months ago

0.0.1

7 months ago