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.
bun add @calap/pcall zod
A procedure is a way to define a function which validates its input and output.
import { z } from 'zod'
import { procedure } from '@calap/pcall'
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.
pc().input(z.string()) // single schema
pc().input({ name: z.string() }) // will be wrapped in z.object
pc().input(z.object({ name: z.string() })) // same as above
- The procedure is also re-exported as
pc
for convenience.
Guaranteed type safety at compile and runtime.
- 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
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}!`)
2.1.1. Chaining middlewares.
- 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)
})
2.1.2. Reusing middlewares.
- 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}!`)
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 { pc } from '@calap/pcall'
import { db, postSchema } from './db'
import { auth } from './auth'
export const getPost = pc()
.input({ postId: z.coerce.number() })
.output(postSchema)
.action(async (c) => await db.posts.findById(c.input.postId))
export const createPost = pc()
.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.
2.2.1. Server 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>
}
2.2.2. Client component with React Query.
// components/post-form.tsx
'use client'
import { useMutation } from '@tanstack/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>
)
}
Compose procedures using a router.
import { router, procedure } from '@calap/pcall'
const usersRouter = router({
list: pc().action(async () => await db.users.find()),
create: pc()
.input({ name: z.string() })
.action(async ({ input }) => {
return await db.users.create(input)
}),
})
export const app = router({
ping: pc().action(() => 'pong'),
users: usersRouter,
})
// export the type for the client if needed
export type AppRouter = typeof app
Serve the app with the standalone server. Powered by the blazing fast Bun HTTP server.
import { serve } from '@calap/pcall'
import { app } from './app'
const server = serve(app)
console.log(`🔥 Listening at ${server.url.href}`)
Run the server and call the procedures over the network.
bun run server.ts
curl -X POST 'localhost:8000?p=ping' # -> pong
curl -X POST 'localhost:8000?p=users.list' # -> [...]
The router can be adapted to any library, framework or service which follows the web standard HTTP request and response format.
4.1.1. Next.js.
- Use the router in a Next.js API route.
// app/api/route.ts
import { handle } from '@calap/pcall/next'
const app = router({
ping: pc().action(() => 'pong'),
})
export const POST = handle(app)
4.1.2. Bun.
- This is what the standalone server uses under the hood.
import { handle } from '@calap/pcall/bun'
const app = router({
ping: pc().action(() => 'pong'),
})
export default handle(app)
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'),
}
},
})
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 '@calap/pcall'
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.
import { useQuery } from '@tanstack/react-query'
import { client } from '@calap/pcall'
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(),
})
// ...
}