UNPKG

bunway

Version:

Express-style routing toolkit built natively for Bun.

149 lines 5.77 kB
import type { BodyInit } from "bun"; import { type BodyParserOptions, type ResolvedBodyParserOptions } from "../config"; /** * Core request/response primitives used by bunWay and passed to every handler. * * Quick start: * ```ts * app.get("/users/:id", async (ctx) => { * const id = ctx.req.param("id"); * const body = await ctx.req.parseBody(); * return ctx.res.json({ id, body }); * }); * ``` * * {@link WayRequest} wraps Bun's {@link Request}, adding express-like helpers * such as `params`, `query`, `locals`, and body parsing utilities while keeping * the original streaming behaviour. {@link WayResponse} offers a small fluent * API around {@link Response} so you can build replies with `res.json()`, * `res.text()`, or `res.send()`. {@link WayContext} simply packages both for * ergonomic middleware composition. */ type ParsedBodyType = "json" | "urlencoded" | "text"; interface BodyParseErrorState { status: number; message: string; } /** * Decorates the incoming {@link Request} with routing and parsing helpers. * * ```ts * app.post("/echo", async (ctx) => { * const body = await ctx.req.parseBody(); * console.log(ctx.req.headers.get("content-type")); * return ctx.res.json({ received: body }); * }); * ``` */ export declare class WayRequest { private readonly originalRequest; private readonly parsedUrl; private readonly localsStore; private paramsStore; private bodyValue; private _rawBody; private _rawText; private _bodyParsed; private _bodyType; private _bodyParseError; private bodyParserDefaults; private bodyParserOverrides; constructor(req: Request, parserConfig?: ResolvedBodyParserOptions); get original(): Request; /** Snapshot of current route params (mutable on purpose for express parity). */ get params(): Record<string, string>; /** Allows the router or middleware to replace params in one go. */ set params(value: Record<string, string>); /** Convenience helper mirroring Express' `req.param(name)` lookup. */ param(key: string): string | undefined; /** Fully-qualified request URL. */ get url(): string; /** Path segment (no query string). Equivalent to `new URL(req.url).pathname`. */ get pathname(): string; /** Alias for `pathname` for those used to Express' `req.path`. */ get path(): string; /** Raw query string portion (including leading `?`). */ get search(): string; /** Live {@link URLSearchParams} view of the request query. */ get query(): URLSearchParams; /** Parsed body payload once a parser has run. */ get body(): any; /** Shared per-request state bag useful for communication between middleware. */ get locals(): Record<string, any>; get method(): string; get headers(): Headers; get bodyType(): ParsedBodyType | null; get bodyParseError(): BodyParseErrorState | null; /** True when a body parser (auto or manual) already produced a result. */ isBodyParsed(): boolean; /** Merge caller-provided overrides with the request-scoped defaults. */ applyBodyParserOverrides(overrides: BodyParserOptions): void; getBodyParserConfig(): ResolvedBodyParserOptions; /** * Persist successful parsing state. Called by the individual parser helpers. */ setParsedBody(value: any, type: ParsedBodyType): void; setBodyParseError(status: number, message: string): void; /** Lazy-load the request body as bytes. Cached so multiple calls are cheap. */ rawBody(): Promise<Uint8Array>; rawText(): Promise<string>; tryParseJson(options: Required<ResolvedBodyParserOptions["json"]>): Promise<boolean>; tryParseUrlencoded(options: Required<ResolvedBodyParserOptions["urlencoded"]>): Promise<boolean>; tryParseText(options: Required<ResolvedBodyParserOptions["text"]>): Promise<boolean>; autoParseBody(config: ResolvedBodyParserOptions): Promise<void>; parseBody(overrides?: BodyParserOptions): Promise<any>; } /** * Fluent builder around {@link Response} for ergonomic reply construction. * * ```ts * return ctx.res.status(201).json({ created: true }); * // or return ctx.res.ok({ created: true }); * ``` */ export declare class WayResponse { private _headers; private _status; private _last; status(code: number): this; /** Replace/append a header to the backing response state. */ header(name: string, value: string): this; /** Serialize data as JSON and return a Response. */ json(data: any): Response; /** Serialize data as plain text. */ text(data: string): Response; /** Construct a Response using whatever body the caller supplies. */ send(data: BodyInit): Response; get statusCode(): number; get headers(): Headers; /** Convenience 200 helper returning JSON when data is supplied. */ ok(data?: any): Response; /** HTTP 201 helper mirroring express' `res.created`. */ created(data?: any): Response; /** Respond with a 204 No Content. */ noContent(): Response; get last(): Response | null; } export type NextFunction = () => Promise<void>; /** * Container passed to every middleware/handler combining {@link WayRequest} * and {@link WayResponse}. Most apps interact with bunWay exclusively through * this object. * * ```ts * app.use(async (ctx, next) => { * console.log(ctx.req.method, ctx.req.path); * await next(); * }); * ``` */ export declare class WayContext { readonly req: WayRequest; readonly res: WayResponse; /** Instantiate a context for the given request and optional body parser conf. */ constructor(req: Request, options?: { bodyParser?: ResolvedBodyParserOptions; }); } export {}; //# sourceMappingURL=context.d.ts.map