defineRequest
Declares a typed HTTP request endpoint.
@defjs/core · Function
Signature
function defineRequest< const M extends string, const P extends string, TInput extends AnyStruct | undefined = undefined, TOutput extends AnyStruct | undefined = undefined, TError extends AnyStruct | undefined = undefined, >( definition: ResponseDeclaration<TOutput, TError> & { input?: TInput; method: M; operation?: string; path: P; } & BuilderField<NoInfer<TInput>, HttpRequestShape<NoInfer<P>, NoInfer<M>>>, ): RequestEndpoint< EndpointArgs<TInput>, RequestSuccessData<TOutput>, RequestErrorData<TError>, DeclaredResponse<TOutput> >;
Pass method, path, an optional input struct, and the single output and
error structs. Call the returned operation with a client and, when declared, the input.
The contract is method, path, an optional input struct, optional
output and error structs, and an optional operation. A declared input
always requires an explicit builder. input only defines the parameters;
the builder alone decides where each value goes. Only definitions without
input may omit builder. ResponseDeclaration and BuilderField are
internal helper types: output and error are required only when the
matching type parameter is a struct, and builder is
(input: BuilderInput<TInput>) => HttpRequestShape when input is declared.
output is one struct for the 2xx body; error is one struct for every
non-2xx body. Neither is keyed by status. A declaration is an assertion:
omitting one means that body is never read.
Parameters
Prop
Type
definition ResponseDeclaration<TOutput, TError> & {
input?: TInput;
method: M;
operation?: string;
path: P;
} & BuilderField<NoInfer<TInput>, HttpRequestShape<NoInfer<P>, NoInfer<M>>>Request contract (method, path, input, builder, output).
Returns
An operation (client, ...input) => Promise<error-first tuple>.
The checked example file passes the whole input object as path. This snippet maps individual fields into path and query instead:
Examples
const getUser = defineRequest({
method: 'GET',
path: '/users/:id',
input: struct.object({ id: struct.number(), verbose: struct.boolean() }),
builder: (input) => ({ path: { id: input.id }, query: { verbose: input.verbose } }),
output: struct.object({ id: struct.number(), name: struct.string() }),
})import { defineRequest, struct } from "@defjs/core"; const getUser = defineRequest({ method: "GET", path: "/users/:id", input: struct.object({ id: struct.number() }), builder: (input) => ({ path: input }), output: struct.object({ id: struct.number(), name: struct.string() }), error: struct.object({ message: struct.string() }), });