UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

41 lines (40 loc) 2.23 kB
import type { Endpoint } from "./Endpoint.js"; /** * A function that handles a endpoint request, with a payload and returns a result. * * @param payload The payload of the request is the result of merging the `{placeholder}` path parameters and `?a=123` query parameters from the URL, with the body of the request. * - Payload is validated by the payload validator for the `Endpoint`. * - If the body of the `Request` is a data object (i.e. a plain object), then body data is merged with the path and query parameters to form a single flat object. * - If payload is _not_ a data object (i.e. it's another JSON type like `string` or `number`) then the payload include the path and query parameters, and a key called `content` that contains the body of the request. * * @param request The raw `Request` object in case it needs any additional processing. * * @returns The correct `Result` type for the `Endpoint`, or a raw `Response` object if you wish to return a custom response. */ export type EndpointCallback<P, R> = (payload: P, request: Request) => R | Response | Promise<R | Response>; /** * Object combining an abstract `Endpoint` and an `EndpointCallback` implementation. */ export interface EndpointHandler<P, R> { readonly endpoint: Endpoint<P, R>; readonly callback: EndpointCallback<P, R>; } /** * Any handler (purposefully as wide as possible for use with `extends X` or `is X` statements). */ export type AnyEndpointHandler = EndpointHandler<any, any>; /** * List of `EndpointHandler` objects objects that can handle requests to an `Endpoint`. */ export type EndpointHandlers = ReadonlyArray<AnyEndpointHandler>; /** * Handler a `Request` with the first matching `EndpointHandlers`. * * 1. Define your `Endpoint` objects with a method, path, payload and result validators, e.g. `GET("/test/{id}", PAYLOAD, STRING)` * 2. Make an array of `EndpointHandler` objects combining an `Endpoint` with a `callback` function * - * * @returns The resulting `Response` from the first handler that matches the `Request`. * @throws `NotFoundError` if no handler matches the `Request`. */ export declare function handleEndpoints(request: Request, endpoints: EndpointHandlers): Promise<Response>;