Dumb Simple Typescript RPC!
npm install @tianhuil/simple-trpc -S
- Zero codegen.
- Zero runtime dependencies (only dependencies are for typing, development, and testing).
- Uses pure typescript to ensure typesafety.
- Support for Express and Koa.
Typesafe RPC call in three simple steps:
This is the interface
// interface.ts
import { IRpc, RpcRet } from '@tianhuil/simple-trpc'
export interface IUser {
id: number
name: string
}
export interface IExampleRPC extends IRpc<IExampleRPC> {
add(x: number, y: number): Promise<RpcRet<number>>
user(id: number): Promise<RpcRet<IUser>>
}
The interface IRpc
ensure typesafety. All methods return promises of
type RpcRet<T> = { data: T } | { error: string }
which supports both errors and data
// server.ts
import { data, error } from '@tianhuil/simple-trpc'
import { IExampleRPC } from './interface'
class ExampleRPCImpl implements IExampleRPC {
public add = async (x: number, y: number) => data(x + y)
public user = async (id: number) => {
if (id === 5) {
return data({id, name: `Bob 5`})
} else {
return error('No such User')
}
}
}
registerExpressHandler<IExampleRPC>(expressApp, new RPCImpl())
// or registerKoaHandler<IExampleRPC>(koaApp, new RPCImpl())
// client.ts
import { makeClient, httpConnector } from '@tianhuil/simple-trpc'
import { IExampleRPC } from './interface'
const client = makeClient<IExampleRPC>(httpConnector('http://example.com'))
async function main() {
console.log(await client.add(2, 3))
const result = await client.user(5)
switch (result.type) {
case 'data': {
console.log(result.data)
break
}
case 'error': {
console.log(`Encountered error: ${result.error}`)
break
}
}
}
For more details, see example/
folder to see a working example.
- Open the
package.json
and run the corresponding scripts. - View the client and server code for Express- and Koa-specific examples
The protocol uses json serialization between client and server. All results are passed asynchronously through promisses. Typesafety comes from typescript's type system. On each call:
- The client serializes the function name and arguements, sending them to the server.
- The server deserializes this, runs the computation on it's implementation, serializes the result, and sends them (or an error) back to the client.
- The client deserializes the result returned from the server as javascript objects.
Simply pass the authentication token (e.g. JWT) as one of the parameters to the handler and return an error if a user is not authorized.