error$

API for the error$ function

This function will be used from the server-side, in order to throw errors on the client side and break out of running middlewares.

Usage

import {
  error$,
  hideRequest,
  middleware$,
  pipe$,
  query$,
  response$,
} from '@prpc/solid'
import { z } from 'zod'

const myMiddleware1 = middleware$(({ request$ }) => {
  console.log('ua', request$.headers.get('user-agent'))
  const random = Math.random()
  const test = random > 0.5 ? 'test' : null
  console.log({ test })
  return { test }
})

const middleWare2 = pipe$(myMiddleware1, (ctx) => {
  if (!ctx.test) {
    return error$('Expected test to be defined')
    // this will throw an error on the client side and will break out of the middlewares
  }
  return {
    test: ctx.test,
    o: 1,
  }
})

const middleware3 = pipe$(middleWare2, (ctx) => {
  // ctx.test is inferred to be string because we checked it in the previous middleware
  return {
    ...ctx,
    b: 2,
  }
})

export const add = query$(
  ({ payload, ctx$ }) => {
    console.log({ ctx$: hideRequest(ctx$) })
    const result = payload.a + payload.b
    return response$(
      { result },
      {
        headers: {
          'set-cookie': 'solid-testing=1',
        },
      }
    )
  },
  'add',
  z.object({
    a: z.number().max(5),
    b: z.number().max(10),
  }),
  middleware3
)