3.0.1 • Published 5 years ago
@borderless/json-rpc v3.0.1
JSON RPC
Tiny, mostly compliant JSON-RPC 2.0 implementation.
This package intentionally doesn't implement the "arguments" form of request parameters. This is when the input params can be an object or an ordered array representing the object. Instead, you can pass any JSON params over the wire.
Installation
npm install @borderless/json-rpc --saveUsage
This package makes no assumptions about the transportation layer, for client or server.
Methods
type Methods = {
hello: {
request: {};
response: string;
};
echo: {
request: { arg: string };
response: string;
};
};Server
The server accepts a dictionary of resolvers.
import { createServer } from "@borderless/json-rpc";
const server = createServer<Methods>({
hello: (_) => "Hello World!",
echo: ({ arg }) => arg,
});
const res = await server({
jsonrpc: "2.0",
id: "test",
method: "hello",
}); //=> { jsonrpc: "2.0", id: "test", result: "Hello World!" }Client
The client accepts a function to send the JSON-RPC request.
import { createClient } from "@borderless/json-rpc";
const client = createClient(async (payload) => {
const res = await fetch("...", {
method: "POST",
body: JSON.stringify(payload),
headers: {
"Content-Type": "application/json",
},
});
return res.json();
});
const result = await client({
method: "hello",
params: {},
}); //=> "Hello World!"
const results = await client.many([
{
method: "hello",
params: {},
},
{
method: "echo",
params: { arg: "Test" },
},
]); //=> ["Hello World!", "Test"]License
MIT
3.0.1
5 years ago