[]previous and next page

apiHandler

Builds an API handler with validated input and a typed context.

Builds an API handler with validated input and a typed context.

Import#

ts
import { apiHandler } from "@shadow-js/dusk/server";

Signature#

ts
function apiHandler<
  B extends StandardSchemaV1 | undefined = undefined,
  Q extends StandardSchemaV1 | undefined = undefined,
>(
  options: ApiHandlerOptions<B, Q>,
  handler: (
    context: ApiContext<
      B extends StandardSchemaV1 ? InferOutput<B> : undefined,
      Q extends StandardSchemaV1 ? InferOutput<Q> : undefined
    >,
  ) => ApiResult | Promise<ApiResult>,
): ApiHandler

Parameters#

Name Description
options Schemas and middleware.
handler Receives { event, body, query }, all validated.

Returns#

An ApiHandler to use as GET, POST, ...

Throws#

  • ValidationError (status 400) from the handler call when input fails its schema.

Examples#

ts
export const POST = apiHandler({ body: z.object({ title: z.string() }) }, ({ body }) => json(body, { status: 201 }));