UNPKG

@intuitionrobotics/thunderstorm

Version:
37 lines 2.14 kB
import { type NextFunction, type Request, type RequestHandler, type Response } from "express"; import { type ApiTypeBinder } from "../../../shared/types.js"; /** * An Express request typed off the same `ApiTypeBinder` the endpoint declares, * so `req.body` / `req.query` and the handler's return value are all typed. */ export type TypedRequest<Binder extends ApiTypeBinder<any, any, any, any>> = Request<Record<string, string>, Binder["response"], Binder["body"], Binder["queryParams"]>; /** * A plain endpoint handler: receives the typed request (plus the raw `res`/`next` * for the rare stream/redirect case) and usually just `return`s a value. */ export type TypedHandler<Binder extends ApiTypeBinder<any, any, any, any>> = (req: TypedRequest<Binder>, res: Response, next: NextFunction) => Promise<Binder["response"] | void> | Binder["response"] | void; export type HandlerOptions = { printResponse?: boolean; }; /** * Wrap a plain typed handler fn as an Express `RequestHandler`. * * Why a wrapper is needed at all on Express 4: a thrown/rejected async handler * is NOT forwarded to `app.use((err,…)=>)` — so we `.catch(next)` to route it * to the app-level `terminalErrorHandler`. We also auto-serialize the return * value (object→json, "<html…>"→html, else text), matching the legacy * `ServerApi.call()` behavior so handlers can simply `return`. * * A handler may instead write to `res` directly (stream/SSE/redirect): once * `res.headersSent`, autoSend is a no-op. Rule: return a value XOR write `res`. */ export declare function handler<Binder extends ApiTypeBinder<any, any, any, any>>(fn: TypedHandler<Binder>, opts?: HandlerOptions): RequestHandler; /** * A redirect endpoint as an Express `RequestHandler` — the functional * replacement for the old `ServerApi_Redirect`. Appends the incoming query * params to the target URL (same shape the class produced) and redirects. * * router.all("/old-path", redirectHandler(301, "/api/v1/new-path")); */ export declare function redirectHandler(responseCode: number, redirectUrl: string): RequestHandler; //# sourceMappingURL=handler.d.ts.map