Skip to content

borderless/json-rpc

Repository files navigation

JSON RPC

NPM version NPM downloads Build status Test coverage

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 --save

Usage

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