typed-json-rpc
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

typed-json-rpc

Simple, statically typed and ergonomic way to do async communications (events, workers, http requests) with json-rpc

Install

npm install typed-json-rpc

Describe your API

export interface Api {
  sum: (x: number, y: number) => number
  increase: (x: number) => number
}

Create your API implementation as request handler

const requestHandler = createRequestHandler<Api>({
  increase: (x) => {
    return x + 1
  },
  sum: (x, y) => x + y,
})

Create a client

const sender = createHttpSender()
const client = createJsonRpcClient<Api>(sender)

And call your API

const x = await client.increase(100)
const y = await client.sum(1,2)

All this code can be used for any type of async communication. The difference is how you send your requests and responses.

Http sender example

export const createHttpSender = (url: string): RequestSender => ({
  sendRequest(request: JsonRpcRequest) {
    return axios
      .post<JsonRpcResponse, AxiosResponse<JsonRpcResponse>>(
        url,
        request,
      ).then((x) =>
        'error' in x.data ? Promise.reject(x.data.error) : x.data.result,
      )
  },
})

Express responses

app.post('/', async (req, res) => {
  const response = await requestHandler.handleRequest(req.body)
  return res.status(200).json(response)
})

Full http example

Worker and EventEmitter examples

Package Sidebar

Install

npm i typed-json-rpc

Weekly Downloads

3

Version

1.1.0

License

MIT

Unpacked Size

15.9 kB

Total Files

19

Last publish

Collaborators

  • ptol