- Notifications
You must be signed in to change notification settings - Fork0
lorefnon/ts-json-rpc
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
LightweightJSON-RPC solution for TypeScript projects
- 👩🔧 Service definition through Zod-based contracts
- 📜 JSON-RPC 2.0 protocol
- 🕵️ Full IDE autocompletion
- 🪶 Tiny footprint (< 1kB)
- 🌎 Support for Deno and edge runtimes
- 🚫 No code generation step
Define a shared service contract and export the type of service:
import{z}from"zod";importtype{ZServiceType}from"@lorefnon/ts-json-rpc/lib/zod";import{ZService}from"@lorefnon/ts-json-rpc/lib/zod";exportconstMyServiceDef=ZService.define({hello:z.function().args(z.string()).returns(z.string().promise()),// More methods here ...});exporttypeMyService=ZServiceType<typeofMyServiceDef>// { hello: (arg: string) => Promise<string>, ... }
Define a server-side implementation of this service:
exportconstMyServiceImpl=MyServiceDef.implement(()=>({asynchello(name){// name is inferred as stringreturn`Hello${name}!`;},// Implement other methods...}));
Create a server with a route to handle the API requests:
importexpressfrom"express";import{rpcHandler}from"@lorefnon/ts-json-rpc/lib/express";constapp=express();app.use(express.json());app.post("/api",rpcHandler(MyServiceImpl));app.listen(3000);
NoteYou can also use @lorefnon/ts-json-rpc in servers other than Express.Check out to docs below forexamples.
On the client-side, import the shared type and create a typedrpcClient
with it:
import{rpcClient,HttpPostTransport}from"@lorefnon/ts-json-rpc/lib/client";// Import the type (not the implementation!)importtype{MyService}from"../shared/MyService";// Create a typed client:constclient=rpcClient<MyService>({transport:newHttpPostTransport({url:"http://localhost:3000/api"})});// Call a remote method:console.log(awaitclient.hello("world"));
That's all it takes to create a type-safe JSON-RPC API. 🎉
You can play with a live example over at StackBlitz:
It is common for services to be created per request.DefaultServiceImpl
in above exampleis a service factory ie. a function that creates and returns an implementation of the service contract.
rpcHandler will invoke this function for every request to create a service object that handles that particularrequest.
This is convenient if you need to access the request (more on this below) but if you don't, instead of a functionyou could also create an instance and pass that to rpcHandler:
app.post("/api",rpcHandler(DefaultServiceImpl({})));
Now, we have a singleton service that handles all requests.
The function passed toServiceDef.implement
can accept a context argument which is available to all the methods.
interfaceServiceContext{currentUser?:{name:string}}exportconstMyServiceImpl=ServiceDef.implement((context:ServiceContext)=>({asynchello(){return`Hello${context.currentUser?.name??"Stranger"}!`;},// Implement other methods...}));
You are responsible for passing thiscontext
toDefaultServiceImpl
.
Most common use case for context is to get access to the request object.
So, by default rpcHandler will simply pass the request object to service factory as context.
However, if you want to ensure that your service implementation is not tied to a specific server implementation (eg. express) you can alsoextract what you need from the request and pass it to the service factory.
app.post("/api",rpcHandler((req)=>MyServiceImpl(req.headers)));
This is also useful if you need to inject any additional objects (eg. database pool instance) into the service.
The generic@lorefnon/ts-json-rpc/server
package can be used with any server framework or (edge-) runtime.
WithFastify, you would use@lorefnon/ts-json-rpc
like this:
import{handleRpc,isJsonRpcRequest}from"@lorefnon/ts-json-rpc/lib/server";fastify.post("/api",async(req,reply)=>{if(isJsonRpcRequest(req.body)){constres=awaithandleRpc(req.body,Service(req));reply.send(res);}});
A client can send custom request headers by providing agetHeaders
function:
constclient=rpcClient<MyService>(apiUrl,{getHeaders(){return{Authorization:auth,};},});
NoteThe
getHeaders
function can also beasync
.
To include credentials in cross-origin requests, passcredentials: 'include'
as option.
While@lorefnon/ts-json-rpc
itself does not provide any built-in UI framework integrations,you can pair it withreact-api-query,a thin wrapper aroundTanStack Query. A type-safe match made in heaven. 💕
MIT
This implementation is based on past work byFelix Gnassintyped-rpc.
The typed-rpc repo is more minimal in its focus (eg. runtime type checking is explicitly not a goal)and does not appear to be accepting pull requests.
About
Type-safe codegen-free isomorphic RPC solution for Typescript