middleware$

API for the middleware$ function

Functions that will run before the query function. Useful for authentication, logging, etc.

Usage

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

const myMiddleware1 = middleware$(({ request$ }) => {
  console.log('req', request$)
  return Math.random() > 0.5 ? { test: true } : { test: null }
})

export const add = query$(
  ({ payload, ctx$ }) => {
    console.log({ ctx$ }) // ctx$ is inferred to be { test: boolean | null }
    const result = payload.a + payload.b
    return response$(
      { result },
      {
        headers: {
          'set-cookie': 'solid-testing=1',
        },
      }
    )
  },
  'add',
  z.object({
    a: z.number(),
    b: z.number(),
  }),
  myMiddleware1
)

Another Syntax

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

export const cleanSyntaxQuery = query$({
  queryFn: async ({ payload, request$, ctx$ }) => {
    ctx$.test
    ctx$.b
    console.log('called', request$.headers.get('user-agent'))
    return response$({ result: payload.a + payload.b })
  },
  key: 'cleanSyntaxQuery',
  schema: z.object({
    a: z.number().max(5),
    b: z.number().max(10),
  }),
  // middleware3 was returned from `middleware$`
  middlewares: [middleware3],
})

If you want to pipe a middleware, check out the pipe function.