typed-remote-procedure-call
v3.0.1
Published
Library for typed RPC
Readme
If you like this project, please support it with a star on Github 🌟
typed-remote-procedure-call
This library provides a convenient way to create transport-agnostic typed RPC It consists of two parts - caller and executor.
Possible use cases:
- Frontend (caller) - HTTP - Backend (executor)
- Backend (caller) - Websocket - Frontend (executor)
- Host web app (caller) - Message bus - Iframe (executor)
- Iframe (caller) - Message bus - Host web app (executor)
- Electron browser thread (caller) - Message bus - Electron native thread (executor)
Installation
npm install --save typed-remote-procedure-call
# or
yarn add typed-remote-procedure-callUsage
First you need to declare your operations API
type Methods = {
add: (a: number; b: number) => Promise<number>;
createUser: (user: { name: string }) => Promise<{ id: number; name: string }>;
};Then you create an executor on one side of communication:
import { createExecutor, ExecutionRequest, ExecutionResponse } from 'typed-remote-procedure-call';
const executor = createExecutor<Methods>({
add: async (a: number; b: number ) => a + b,
createUser: async (user: { name: string }) => ({ id: 1, name: input.name }),
});
export const handleRequestFromCallerSide = async (request: ExecutionRequest): Promise<ExecutionResponse> =>
executor.execute(request);Then you create an rpc caller on another side of communication:
import { createRPC, ExecutionRequest } from 'typed-remote-procedure-call';
const rpc = createRPC<Methods>({
send: async (request: ExecutionRequest) => sendRequestToExecutionSide(request), // Here you can use any transport: HTTP, Websocket, some message bus
});Then you can call the operations:
const user = await rpc.createUser({ name: 'John' });
const sum = await rpc.add(5, 2);