@tianhuil/simple-trpc
v1.9.3
Published
Dumb Simple Typescript RPC. Zero Codegen (Uses Pure Typescript. Zero dependencies (small footprint). Support for Express and Koa servers.
Downloads
19
Readme
simple-trpc
Dumb Simple Typescript RPC!
Install
npm install @tianhuil/simple-trpc -S
Features
- Zero codegen.
- Zero runtime dependencies (only dependencies are for typing, development, and testing).
- Uses pure typescript to ensure typesafety.
- Support for Express and Koa.
Usage
Typesafe RPC call in three simple steps:
Step 1: Define the typesafe interface
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
Step 2: Implement the interface as a class and register
// 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())
Step 3: Connect the client and use it!
// 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
}
}
}
Learn More
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
How does it work?
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.
Frequently Asked Questions
How do you handle authentication?
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.