Tiny, type-safe JSON-RPC 2.0 implementation.
npm install @borderlesslabs/json-rpc --save
# Peer dependencies.
npm install io-ts fp-ts --save
This package makes no assumptions about the transportation layer, for client or server.
The methods definition uses io-ts
to encode and decode requests or responses.
import * as t from "io-ts";
const methods = {
hello: {
// `request` is required, even when empty.
request: t.type({}),
response: t.string
},
echo: {
// Specify `request` parameters as keys of the object.
request: t.type({ arg: t.string }),
response: t.string
}
};
The server takes the methods and a dictionary of matching resolvers.
import { createClient } from "@borderlesslabs/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!" }
The client takes the methods and a function to send
the JSON-RPC request.
import { createClient } from "@borderlesslabs/json-rpc";
const client = createClient(methods, async x => {
const res = await fetch("...", {
body: JSON.stringify(x),
headers: {
"Content-Type": "application/json"
}
});
return res.json();
});
const result = await client({
method: "hello",
params: {}
}); //=> "Hello World!"
const results = await client.batch(
{
method: "hello",
params: {}
},
{
method: "echo",
params: { arg: "Test" }
}
); //=> ["Hello World!", "Test"]
MIT