A modern isomorphic typescript client for JSON-RPC 2.0. The goal of this project is to provide maximum ergonomics for typescript projects (autocomplete all the things!). This app could be used standalone, or as a dependency for an SDK generator.
Check out the Open RPC Ecosystem for more tools.
Features
Feature | Supported |
---|
Isomorphism | ✅ |
Batch Support | ✅ |
Contract Support | ✅ |
Installation
npm install jsonrpc-ts-client --save
or
yarn add jsonrpc-ts-client
Basic Usage
import JSONRPC from 'jsonrpc-ts-client'
interface UserDto {
name: string,
occupation: string,
}
const client = new JSONRPC({
url: 'https://foo.com/jsonrpc'
})
const response = await client.exec<UserDto>('my_method', { userId: 123 });
if (response.isSuccess()) {
console.log(response.result.name)
console.log(response.result.occupation)
} else if (response.isError()) {
console.log(result.error.message)
console.log(result.error.code)
}
const result = response.unsafeCoerce()
console.log(result.name)
API Contract Declaration Support (Recommended option)
You can make batch requests per the JSON-RPC specification.
import JSONRPC from 'jsonrpc-ts-client'
type MyApiContract = {
getUser: (params: UserParamsDto) => UserDto;
getConfig: () => ConfigDto,
getProduct: (productId: string) => ProductDto,
};
const client = new JsonRpcClient<MyApiContract>({
idGeneratorFn: uuid.v4,
url: JSONRPC_URL,
});
const result = await client.exec("getUser", { userId: 123 });
if (result.isSuccess()) {
console.log(result.user.name)
console.log(result.user.id)
}
Batch Support
import JSONRPC from 'jsonrpc-ts-client'
type MyApiContract = {
getUser: (params: UserParamsDto) => UserDto;
getConfig: () => ConfigDto,
getProduct: (productId: string) => ProductDto,
};
const [user, config] = await client.execBatch([
{ method: "getUser", params: { userId: 123 } },
{ method: "getConfig" },
] as const
);
if (user.isSuccess()) {
console.log(user.name)
console.log(user.id)
}
if (config.isSuccesss()) {
console.log(config.foo)
}
ID Generation
Generate IDs automatically, and/or override or set them on a per-request basis.
import JSONRPC from 'jsonrpc-ts-client'
import uuid from 'uuid'
const client = new JSONRPC({
...
idGeneratorFn: uuid.v4,
})
const response = await client.exec( 'my_method', { userId: 123 }, 'MY_OVERRIDING_ID');