UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

36 lines (35 loc) 2.34 kB
import type { AnyCaller } from "../../util/function.js"; import { type PossibleURL } from "../../util/url.js"; import type { Endpoint } from "./Endpoint.js"; /** * A function that handles an endpoint request, with a payload and returns a result. * * @param payload The payload for the callback combining the `{placeholders}`, `?search` params, and body content (this has been validated against the Endpoint's payload schema). * @param request The original incoming request object. * @param context An additional context argument that can be passed into the callback. * * @returns {Response} Returning a `Response` object (this will pass back to the client without validation). * @returns {R} Returning the return type of the handler (this will be validated against the Endpoint's result schema). */ export type EndpointCallback<P, R, C = void> = (payload: P, request: Request, context: C) => R | Response | Promise<R | Response>; /** A typed endpoint definition paired with its implementation callback. */ export interface EndpointHandler<P, R, C = void> { readonly endpoint: Endpoint<P, R>; readonly callback: EndpointCallback<P, R, C>; } /** Any endpoint handler. */ export type AnyEndpointHandler<C = any> = EndpointHandler<any, any, C>; /** A collection of endpoint handlers that can be matched and invoked by `handleEndpoints()`. */ export type EndpointHandlers<C = void> = Iterable<AnyEndpointHandler<C>>; /** * Handle a `Request` with the first matching endpoint handler after stripping any base-path prefix from the request pathname. * - The original `Request` object is passed through to the callback unchanged. * - Path params and query params are merged before payload validation. * * @param request The input request to handle. * * @param base The base URL for the API, e.g. `https://myapi.com/a/b` * - `pathname` of this URL gets trimmed from `request.path` to form the target path when matching against endpoints, e.g. `/a/b/c/d` will produce `/c/d` for matching. */ export declare function handleEndpoints<C>(base: PossibleURL, handlers: EndpointHandlers<C>, request: Request, context: C, caller?: AnyCaller): Promise<Response>; export declare function handleEndpoints(base: PossibleURL, handlers: EndpointHandlers<void>, request: Request, context?: undefined, caller?: AnyCaller): Promise<Response>;