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

@jcel/rpc

v0.0.13

Published

Remote Procedure Call (RPC) over HTTP with end to end validation and type safety.

Downloads

19

Readme

RPC

Remote Procedure Call (RPC) over HTTP with end to end validation and type safety.

  • Validate any function's input and output with Zod.
  • Use it as a server action in Next.js.
  • Use it as a way to compose a router of procedures and handle HTTP requests.

1. Installation

bun add @jcel/rpc zod

2. Procedure

A procedure is a way to define a function which validates its input and output.

import { z } from 'zod'
import { procedure } from '@jcel/rpc'

const hello = procedure()
  .input({ name: z.string() })
  .output(z.string())
  .action(({ input }) => `Hello ${input.name}!`)

const result = await hello({ name: 'World' })

The validator can be a single zod schema or an object of zod schemas.

procedure().input(z.string()) // single schema
procedure().input({ name: z.string() }) // will be wrapped in z.object
procedure().input(z.object({ name: z.string() })) // same as above
  • If the input is provided, the input value will be inferred and validated accordingly.
const hello = procedure()
  .input(z.string())
  .action(() => {})

hello(1) // error: expected string, got number
  • If the output is provided, the return value of the action will be inferred and validated accordingly.
procedure()
  .output(z.string())
  .action(() => 1) // error: expected string, got number

2.1. Middleware

Add middlewares to the procedure to create a chain of actions. The return value of the middleware will be assigned to the procedures context.

procedure()
  .use(() => {
    return { user: 'foo' }
  })
  .action(({ ctx }) => `Hello ${ctx.user}!`)
  • Think of it as a pipeline where the context is passed from one middleware to another.
async function auth() {
  const session = await getSession() // -> { user } | null
  if (!session) throw new Error('Unauthorized')
  return { user: session.user } // infer non-null user
}

function admin({ ctx }) {
  if (ctx.user.role !== 'admin') {
    throw new Error('Forbidden')
  }
  return ctx
}

procedure()
  .use(auth)
  .use(admin)
  .action(({ ctx }) => {
    console.log('Admin:', ctx.user.name)
  })
  • Define a middleware once and reuse it across multiple procedures.
const authed = procedure().use(auth)

const hello = authed.action(({ ctx }) => `Hello ${ctx.user}!`)
const bye = authed.action(({ ctx }) => `Bye ${ctx.user}!`)

2.2. Next.js Server Actions

Since server actions are just functions, you can use a procedure as a server action in Next.js.

'use server'

import { z } from 'zod'
import { procedure } from '@jcel/rpc'
import { db, postSchema } from './db'
import { auth } from './auth'

export const getPost = procedure()
  .input({ postId: z.coerce.number() })
  .output(postSchema)
  .action(async (c) => await db.posts.findById(c.input.postId))

export const createPost = procedure()
  .use(auth)
  .input({ title: z.string() })
  .output(postSchema)
  .action(async (c) => await db.posts.create(c.input))

Call it from a server or client component.

// app/posts/[id]/page.tsx

import { getPost } from '@/actions'

export default async function Page({ params }) {
  const post = await getPost({ postId: params.id })

  return <div>{post.title}</div>
}
// components/post-form.tsx

'use client'

import { useMutation } from 'react-query'
import { createPost } from '@/actions'

export function PostForm() {
  const [title, setTitle] = useState('')

  const { mutate, error, isPending } = useMutation({
    mutationKey: ['create-post'],
    mutationFn: createPost,
  })

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault()
        mutate({ title })
      }}
    >
      <input value={title} onChange={(e) => setTitle(e.target.value)} />
      {error && <div>{error.message}</div>}
      <button type="submit" disabled={isPending}>
        Submit
      </button>
    </form>
  )
}

3. Router

Compose procedures using a router.

import { router, procedure } from '@jcel/rpc'

const usersRouter = router({
  list: procedure().action(async () => await db.users.find()),
  getById: procedure()
    .input({ userId: z.number() })
    .action(async ({ input }) => {
      return await db.users.findById(input.userId)
    }),
})

export const app = router({
  ping: procedure().action(() => 'pong'),
  users: usersRouter,
})

// export the type for the client if needed
export type AppRouter = typeof app

4. Server

Serve the app with the standalone server. Powered by the blazing fast Bun HTTP server.

import { serve } from '@jcel/rpc'
import { app } from './app'

const server = serve(app)

console.log(`🔥 Listening at ${server.url.href}`)
bun run server.ts

curl -X POST 'localhost:8000?p=ping' # -> pong

curl -X POST 'localhost:8000?p=users.list' # -> [...]

4.1. Adapters

The router can be adapted to any library, framework or service which follows the web standard HTTP request and response format.

  • Use the router in a Next.js API route.
// app/api/route.ts

import { handle } from '@jcel/rpc/next'

const app = router({
  ping: procedure().action(() => 'pong'),
})

export const POST = handle(app)
  • This is what the standalone server uses under the hood.
import { handle } from '@jcel/rpc/bun'
import { app } from './app'

export default handle(app)

4.2 Configuration

Customize the server. The context function will be called on every request and pass the return value to the router so it can be accessed in the procedures.

serve(app, {
  port: 8000,
  context(req) {
    return {
      token: req.headers.get('x'),
    }
  },
})

5. Client

Create a client to call the procedures over the network with end to end type safety. It uses a Proxy and the web standard fetch API under the hood.

import { client } from '@jcel/rpc'
import type { AppRouter } from './server'

const api = client<AppRouter>({ url: 'http://localhost:8000' })

const data = await api.posts.getById({ postId: 1 })

The parameters and return type will be inferred from the router type. There is no need to import the router itself in the client side, just the type.

X. Examples

X.1. Client with React Query

import { useQuery } from 'react-query'
import { client } from '@jcel/rpc'
import type { AppRouter } from './server'

const api = client<AppRouter>({ url: 'http://localhost:8000' })

export function Posts() {
  const { data, error, isLoading } = useQuery({
    queryKey: ['posts'],
    queryFn: () => api.posts.list(),
  })
  // ...
}