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$,
} from '@solid-mediakit/prpc'
import { z } from 'zod'

const myMiddleware1 = middleware$(({ event$ }) => {
  console.log('ua', event$.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$({
  queryFn: ({ payload, ctx$ }) => {
    console.log({ ctx$: hideRequest(ctx$) })
    const result = payload.a + payload.b
    return { result }
  },
  key: 'add',
  schema: z.object({
    a: z.number().max(5),
    b: z.number().max(10),
  }),
  middleware: middleware3,
})