Simple, statically typed and ergonomic way to do async communications (events, workers, http requests) with json-rpc
npm install typed-json-rpc
export interface Api {
sum: (x: number, y: number) => number
increase: (x: number) => number
}
const requestHandler = createRequestHandler<Api>({
increase: (x) => {
return x + 1
},
sum: (x, y) => x + y,
})
const sender = createHttpSender()
const client = createJsonRpcClient<Api>(sender)
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.
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,
)
},
})
app.post('/', async (req, res) => {
const response = await requestHandler.handleRequest(req.body)
return res.status(200).json(response)
})