serverFn
Defines a server function.
Defines a server function. The handler runs only on the server and receives the validated
input and the request event. In a client bundle the build replaces it with a stub that calls
the RPC endpoint (POST /_dusk/fn/<id>).
Defines a typed streaming function without a schema.
Defines a schema-validated ordinary server function.
Defines a server function without an input schema: the input is untrusted unknown, so validate
it yourself (a schema is the better choice).
Import#
ts
import { serverFn } from "@shadow-js/dusk/server";
Signature#
ts
function serverFn<S extends StandardSchemaV1, Item>(
options: StreamingServerFnOptions & { readonly input: S },
handler: (
input: InferOutput<S>,
event: RequestEvent,
) => AsyncIterable<Item> | Promise<AsyncIterable<Item>>,
): ServerFn<InferInput<S>, AsyncIterable<Item>, InferOutput<S>>
function serverFn<Item>(
options: StreamingServerFnOptions,
handler: (
input: unknown,
event: RequestEvent,
) => AsyncIterable<Item> | Promise<AsyncIterable<Item>>,
): ServerFn<unknown, AsyncIterable<Item>, unknown>
function serverFn<S extends StandardSchemaV1, Output>(
options: ServerFnOptions & { readonly input: S; readonly stream?: false },
handler: (input: InferOutput<S>, event: RequestEvent) => Output | Promise<Output>,
): ServerFn<InferInput<S>, Awaited<Output>, InferOutput<S>>
function serverFn<Output>(
options: ServerFnOptions & { readonly stream?: false },
handler: (input: unknown, event: RequestEvent) => Output | Promise<Output>,
): ServerFn<unknown, Awaited<Output>, unknown>
Parameters#
| Name | Description |
|---|---|
options |
Method, input schema, middleware. |
handler |
The server-side implementation. |
options |
Streaming options. |
handler |
Produces items. |
options |
Function options. |
handler |
Implementation. |
options |
Method and middleware. |
handler |
The server-side implementation. |
Returns#
A callable server function.
Throws#
- TypeError for an invalid method, schema or middleware list.
Examples#
ts
export const addTodo = serverFn(
{ input: z.object({ title: z.string().min(1) }), middleware: [requireUser] },
async ({ title }, event) => db.todos.insert({ title, owner: event.get(userKey).id }),
);
ts
const ticks = serverFn({ stream: true }, async function* () { yield 1; });
ts
const echo = serverFn({ input: schema }, value => value);
ts
export const ping = serverFn({}, () => "pong");