typed-json-rpc
v1.1.0
Published
Simple, statically typed and ergonomic way to do async communications (events, workers, http requests) with json-rpc
Downloads
266
Readme
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)
})