npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@lorefnon/ts-json-rpc

v4.3.0

Published

Lightweight JSON-RPC solution for TypeScript projects

Downloads

323

Readme

ts-json-rpc

Lightweight JSON-RPC solution for TypeScript projects

Features:

  • 👩‍🔧 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

Basic Usage

Define a shared service contract and export the type of service:

import { z } from "zod";
import type { ZServiceType } from "@lorefnon/ts-json-rpc/lib/zod";
import { ZService } from "@lorefnon/ts-json-rpc/lib/zod";

export const MyServiceDef = ZService.define({

  hello: z.function()
    .args(z.string())
    .returns(z.string().promise()),

  // More methods here ...
});

export type MyService = ZServiceType<typeof MyServiceDef>
// { hello: (arg: string) => Promise<string>, ... }

Define a server-side implementation of this service:

export const MyServiceImpl = MyServiceDef.implement(() => ({

  async hello(name) { // name is inferred as string
    return `Hello ${name}!`;
  },

  // Implement other methods...
}));

Create a server with a route to handle the API requests:

import express from "express";
import { rpcHandler } from "@lorefnon/ts-json-rpc/lib/express";

const app = express();
app.use(express.json());
app.post("/api", rpcHandler(MyServiceImpl));
app.listen(3000);

Note You can also use @lorefnon/ts-json-rpc in servers other than Express. Check out to docs below for examples.

On the client-side, import the shared type and create a typed rpcClient with it:

import { rpcClient, HttpPostTransport } from "@lorefnon/ts-json-rpc/lib/client";

// Import the type (not the implementation!)
import type { MyService } from "../shared/MyService";

// Create a typed client:
const client = rpcClient<MyService>({
  transport: new HttpPostTransport({
    url: "http://localhost:3000/api"
  })
});

// Call a remote method:
console.log(await client.hello("world"));

That's all it takes to create a type-safe JSON-RPC API. 🎉

Demo

You can play with a live example over at StackBlitz:

Open in StackBlitz

Advanced Usage

Service factories vs singletons

It is common for services to be created per request. DefaultServiceImpl in above example is 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 particular request.

This is convenient if you need to access the request (more on this below) but if you don't, instead of a function you 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.

Service context

The function passed to ServiceDef.implement can accept a context argument which is available to all the methods.

interface ServiceContext {
  currentUser?: { name: string }
}

export const MyServiceImpl = ServiceDef.implement((context: ServiceContext) => ({

  async hello() {
    return `Hello ${context.currentUser?.name ?? "Stranger"}!`;
  },

  // Implement other methods...
}));

You are responsible for passing this context to DefaultServiceImpl.

Accessing the request

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 also extract 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.

Support for other runtimes

The generic @lorefnon/ts-json-rpc/server package can be used with any server framework or (edge-) runtime.

Fastify

With Fastify, 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)) {
    const res = await handleRpc(req.body, Service(req));
    reply.send(res);
  }
});

Sending custom headers

A client can send custom request headers by providing a getHeaders function:

const client = rpcClient<MyService>(apiUrl, {
  getHeaders() {
    return {
      Authorization: auth,
    };
  },
});

Note The getHeaders function can also be async.

CORS credentials

To include credentials in cross-origin requests, pass credentials: 'include' as option.

React hooks

While @lorefnon/ts-json-rpc itself does not provide any built-in UI framework integrations, you can pair it with react-api-query, a thin wrapper around TanStack Query. A type-safe match made in heaven. 💕

License

MIT

Lineage

This implementation is based on past work by Felix Gnass in typed-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.