0.0.3 • Published 1 year ago

@calap/pcall v0.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

PCALL

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 @calap/pcall 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 '@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.
  • 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 { 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.

// 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 '@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>
  )
}

3. Router

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

4. Server

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}`)
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 '@calap/pcall/next'

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

export const POST = handle(app)
  • 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)

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 '@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.

X. Examples

X.1. Client with React Query

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(),
  })
  // ...
}