UNPKG

cf-workers-query

Version:

Automatically cache and revalidate data in Cloudflare Workers. Using the Cache API and Execution Context

941 lines (929 loc) 30.8 kB
import { a as CreateQuery, Q as QueryKey } from '../create-query-BaMMwngc.js'; /** * Type representing a map of parameter indices. */ type ParamIndexMap = Record<string, number>; /** * Type representing a stash of parameters. */ type ParamStash = string[]; /** * Type representing a map of parameters. */ type Params = Record<string, string>; /** * Type representing the result of a route match. * * The result can be in one of two formats: * 1. An array of handlers with their corresponding parameter index maps, followed by a parameter stash. * 2. An array of handlers with their corresponding parameter maps. * * Example: * * [[handler, paramIndexMap][], paramArray] * ```typescript * [ * [ * [middlewareA, {}], // '*' * [funcA, {'id': 0}], // '/user/:id/*' * [funcB, {'id': 0, 'action': 1}], // '/user/:id/:action' * ], * ['123', 'abc'] * ] * ``` * * [[handler, params][]] * ```typescript * [ * [ * [middlewareA, {}], // '*' * [funcA, {'id': '123'}], // '/user/:id/*' * [funcB, {'id': '123', 'action': 'abc'}], // '/user/:id/:action' * ] * ] * ``` */ type Result<T> = [[T, ParamIndexMap][], ParamStash] | [[T, Params][]]; /** * @module * HTTP Status utility. */ type InfoStatusCode = 100 | 101 | 102 | 103; type SuccessStatusCode = 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 226; type DeprecatedStatusCode = 305 | 306; type RedirectStatusCode = 300 | 301 | 302 | 303 | 304 | DeprecatedStatusCode | 307 | 308; type ClientErrorStatusCode = 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451; type ServerErrorStatusCode = 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511; /** * `UnofficialStatusCode` can be used to specify an unofficial status code. * @example * * ```ts * app.get('/unknown', (c) => { * return c.text("Unknown Error", 520 as UnofficialStatusCode) * }) * ``` */ type UnofficialStatusCode = -1; /** * If you want to use an unofficial status, use `UnofficialStatusCode`. */ type StatusCode = InfoStatusCode | SuccessStatusCode | RedirectStatusCode | ClientErrorStatusCode | ServerErrorStatusCode | UnofficialStatusCode; type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; type JSONPrimitive = string | boolean | number | null; type JSONArray = (JSONPrimitive | JSONObject | JSONArray)[]; type JSONObject = { [key: string]: JSONPrimitive | JSONArray | JSONObject | object; }; type InvalidJSONValue = undefined | symbol | ((...args: unknown[]) => unknown); type InvalidToNull<T> = T extends InvalidJSONValue ? null : T; type IsInvalid<T> = T extends InvalidJSONValue ? true : false; /** * symbol keys are omitted through `JSON.stringify` */ type OmitSymbolKeys<T> = { [K in keyof T as K extends symbol ? never : K]: T[K]; }; type JSONValue = JSONObject | JSONArray | JSONPrimitive; type JSONParsed<T> = T extends { toJSON(): infer J; } ? (() => J) extends () => JSONPrimitive ? J : (() => J) extends () => { toJSON(): unknown; } ? {} : JSONParsed<J> : T extends JSONPrimitive ? T : T extends InvalidJSONValue ? never : T extends [] ? [] : T extends readonly [infer R, ...infer U] ? [JSONParsed<InvalidToNull<R>>, ...JSONParsed<U>] : T extends Array<infer U> ? Array<JSONParsed<InvalidToNull<U>>> : T extends Set<unknown> | Map<unknown, unknown> ? {} : T extends object ? { [K in keyof OmitSymbolKeys<T> as IsInvalid<T[K]> extends true ? never : K]: boolean extends IsInvalid<T[K]> ? JSONParsed<T[K]> | undefined : JSONParsed<T[K]>; } : never; /** * Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability. * @copyright from sindresorhus/type-fest */ type Simplify<T> = { [KeyType in keyof T]: T[KeyType]; } & {}; /** * A simple extension of Simplify that will deeply traverse array elements. */ type SimplifyDeepArray<T> = T extends any[] ? { [E in keyof T]: SimplifyDeepArray<T[E]>; } : Simplify<T>; type IsAny<T> = boolean extends (T extends never ? true : false) ? true : false; /** * @module * This module contains some type definitions for the Hono modules. */ type Bindings = object; type Variables = object; type Env = { Bindings?: Bindings; Variables?: Variables; }; type Next = () => Promise<void>; type Input = { in?: {}; out?: {}; outputFormat?: ResponseFormat; }; type BlankInput = {}; interface RouterRoute { path: string; method: string; handler: H; } type HandlerResponse<O> = Response | TypedResponse<O> | Promise<Response | TypedResponse<O>>; type Handler<E extends Env = any, P extends string = any, I extends Input = BlankInput, R extends HandlerResponse<any> = any> = (c: Context<E, P, I>, next: Next) => R; type MiddlewareHandler<E extends Env = any, P extends string = string, I extends Input = {}> = (c: Context<E, P, I>, next: Next) => Promise<Response | void>; type H<E extends Env = any, P extends string = any, I extends Input = BlankInput, R extends HandlerResponse<any> = any> = Handler<E, P, I, R> | MiddlewareHandler<E, P, I>; type NotFoundHandler<E extends Env = any> = (c: Context<E>) => Response | Promise<Response>; type KnownResponseFormat = 'json' | 'text' | 'redirect'; type ResponseFormat = KnownResponseFormat | string; type TypedResponse<T = unknown, U extends StatusCode = StatusCode, F extends ResponseFormat = T extends string ? 'text' : T extends JSONValue ? 'json' : ResponseFormat> = { _data: T; _status: U; _format: F; }; type FormValue = string | Blob; type ParsedFormValue = string | File; type ValidationTargets<T extends FormValue = ParsedFormValue> = { json: any; form: Record<string, T | T[]>; query: Record<string, string | string[]>; param: Record<string, string> | Record<string, string | undefined>; header: Record<string, string>; cookie: Record<string, string>; }; type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer Rest}` ? Rest extends `${infer _Pattern}?` ? `${Name}?` : Name : NameWithPattern; type ParamKey<Component> = Component extends `:${infer NameWithPattern}` ? ParamKeyName<NameWithPattern> : never; type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}` ? ParamKey<Component> | ParamKeys<Rest> : ParamKey<Path>; type ParamKeyToRecord<T extends string> = T extends `${infer R}?` ? Record<R, string | undefined> : { [K in T]: string; }; type InputToDataByTarget<T extends Input['out'], Target extends keyof ValidationTargets> = T extends { [K in Target]: infer R; } ? R : never; type RemoveQuestion<T> = T extends `${infer R}?` ? R : T; declare abstract class FetchEventLike { abstract readonly request: Request; abstract respondWith(promise: Response | Promise<Response>): void; abstract passThroughOnException(): void; abstract waitUntil(promise: Promise<void>): void; } /** * @module * Body utility. */ type BodyDataValueDot = { [x: string]: string | File | BodyDataValueDot; } & {}; type BodyDataValueDotAll = { [x: string]: string | File | (string | File)[] | BodyDataValueDotAll; } & {}; type SimplifyBodyData<T> = { [K in keyof T]: string | File | (string | File)[] | BodyDataValueDotAll extends T[K] ? string | File | (string | File)[] | BodyDataValueDotAll : string | File | BodyDataValueDot extends T[K] ? string | File | BodyDataValueDot : string | File | (string | File)[] extends T[K] ? string | File | (string | File)[] : string | File; } & {}; type BodyDataValueComponent<T> = string | File | (T extends { all: false; } ? never : T extends { all: true; } | { all: boolean; } ? (string | File)[] : never); type BodyDataValueObject<T> = { [key: string]: BodyDataValueComponent<T> | BodyDataValueObject<T>; }; type BodyDataValue<T> = BodyDataValueComponent<T> | (T extends { dot: false; } ? never : T extends { dot: true; } | { dot: boolean; } ? BodyDataValueObject<T> : never); type BodyData<T extends Partial<ParseBodyOptions> = {}> = SimplifyBodyData<Record<string, BodyDataValue<T>>>; type ParseBodyOptions = { /** * Determines whether all fields with multiple values should be parsed as arrays. * @default false * @example * const data = new FormData() * data.append('file', 'aaa') * data.append('file', 'bbb') * data.append('message', 'hello') * * If all is false: * parseBody should return { file: 'bbb', message: 'hello' } * * If all is true: * parseBody should return { file: ['aaa', 'bbb'], message: 'hello' } */ all: boolean; /** * Determines whether all fields with dot notation should be parsed as nested objects. * @default false * @example * const data = new FormData() * data.append('obj.key1', 'value1') * data.append('obj.key2', 'value2') * * If dot is false: * parseBody should return { 'obj.key1': 'value1', 'obj.key2': 'value2' } * * If dot is true: * parseBody should return { obj: { key1: 'value1', key2: 'value2' } } */ dot: boolean; }; type Body = { json: any; text: string; arrayBuffer: ArrayBuffer; blob: Blob; formData: FormData; }; type BodyCache = Partial<Body & { parsedBody: BodyData; }>; declare class HonoRequest<P extends string = '/', I extends Input['out'] = {}> { #private; /** * `.raw` can get the raw Request object. * * @see {@link https://hono.dev/docs/api/request#raw} * * @example * ```ts * // For Cloudflare Workers * app.post('/', async (c) => { * const metadata = c.req.raw.cf?.hostMetadata? * ... * }) * ``` */ raw: Request; routeIndex: number; /** * `.path` can get the pathname of the request. * * @see {@link https://hono.dev/docs/api/request#path} * * @example * ```ts * app.get('/about/me', (c) => { * const pathname = c.req.path // `/about/me` * }) * ``` */ path: string; bodyCache: BodyCache; constructor(request: Request, path?: string, matchResult?: Result<[unknown, RouterRoute]>); /** * `.req.param()` gets the path parameters. * * @see {@link https://hono.dev/docs/api/routing#path-parameter} * * @example * ```ts * const name = c.req.param('name') * // or all parameters at once * const { id, comment_id } = c.req.param() * ``` */ param<P2 extends ParamKeys<P> = ParamKeys<P>>(key: P2 extends `${infer _}?` ? never : P2): string; param<P2 extends RemoveQuestion<ParamKeys<P>> = RemoveQuestion<ParamKeys<P>>>(key: P2): string | undefined; param(key: string): string | undefined; param<P2 extends string = P>(): Simplify<UnionToIntersection<ParamKeyToRecord<ParamKeys<P2>>>>; private getDecodedParam; private getAllDecodedParams; private getParamValue; /** * `.query()` can get querystring parameters. * * @see {@link https://hono.dev/docs/api/request#query} * * @example * ```ts * // Query params * app.get('/search', (c) => { * const query = c.req.query('q') * }) * * // Get all params at once * app.get('/search', (c) => { * const { q, limit, offset } = c.req.query() * }) * ``` */ query(key: string): string | undefined; query(): Record<string, string>; /** * `.queries()` can get multiple querystring parameter values, e.g. /search?tags=A&tags=B * * @see {@link https://hono.dev/docs/api/request#queries} * * @example * ```ts * app.get('/search', (c) => { * // tags will be string[] * const tags = c.req.queries('tags') * }) * ``` */ queries(key: string): string[] | undefined; queries(): Record<string, string[]>; /** * `.header()` can get the request header value. * * @see {@link https://hono.dev/docs/api/request#header} * * @example * ```ts * app.get('/', (c) => { * const userAgent = c.req.header('User-Agent') * }) * ``` */ header(name: string): string | undefined; header(): Record<string, string>; /** * `.parseBody()` can parse Request body of type `multipart/form-data` or `application/x-www-form-urlencoded` * * @see {@link https://hono.dev/docs/api/request#parsebody} * * @example * ```ts * app.post('/entry', async (c) => { * const body = await c.req.parseBody() * }) * ``` */ parseBody<Options extends Partial<ParseBodyOptions>, T extends BodyData<Options>>(options?: Options): Promise<T>; parseBody<T extends BodyData>(options?: Partial<ParseBodyOptions>): Promise<T>; private cachedBody; /** * `.json()` can parse Request body of type `application/json` * * @see {@link https://hono.dev/docs/api/request#json} * * @example * ```ts * app.post('/entry', async (c) => { * const body = await c.req.json() * }) * ``` */ json<T = any>(): Promise<T>; /** * `.text()` can parse Request body of type `text/plain` * * @see {@link https://hono.dev/docs/api/request#text} * * @example * ```ts * app.post('/entry', async (c) => { * const body = await c.req.text() * }) * ``` */ text(): Promise<string>; /** * `.arrayBuffer()` parse Request body as an `ArrayBuffer` * * @see {@link https://hono.dev/docs/api/request#arraybuffer} * * @example * ```ts * app.post('/entry', async (c) => { * const body = await c.req.arrayBuffer() * }) * ``` */ arrayBuffer(): Promise<ArrayBuffer>; /** * Parses the request body as a `Blob`. * @example * ```ts * app.post('/entry', async (c) => { * const body = await c.req.blob(); * }); * ``` * @see https://hono.dev/docs/api/request#blob */ blob(): Promise<Blob>; /** * Parses the request body as `FormData`. * @example * ```ts * app.post('/entry', async (c) => { * const body = await c.req.formData(); * }); * ``` * @see https://hono.dev/docs/api/request#formdata */ formData(): Promise<FormData>; /** * Adds validated data to the request. * * @param target - The target of the validation. * @param data - The validated data to add. */ addValidatedData(target: keyof ValidationTargets, data: {}): void; /** * Gets validated data from the request. * * @param target - The target of the validation. * @returns The validated data. * * @see https://hono.dev/docs/api/request#valid */ valid<T extends keyof I & keyof ValidationTargets>(target: T): InputToDataByTarget<I, T>; /** * `.url()` can get the request url strings. * * @see {@link https://hono.dev/docs/api/request#url} * * @example * ```ts * app.get('/about/me', (c) => { * const url = c.req.url // `http://localhost:8787/about/me` * ... * }) * ``` */ get url(): string; /** * `.method()` can get the method name of the request. * * @see {@link https://hono.dev/docs/api/request#method} * * @example * ```ts * app.get('/about/me', (c) => { * const method = c.req.method // `GET` * }) * ``` */ get method(): string; /** * `.matchedRoutes()` can return a matched route in the handler * * @see {@link https://hono.dev/docs/api/request#matchedroutes} * * @example * ```ts * app.use('*', async function logger(c, next) { * await next() * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => { * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]') * console.log( * method, * ' ', * path, * ' '.repeat(Math.max(10 - path.length, 0)), * name, * i === c.req.routeIndex ? '<- respond from here' : '' * ) * }) * }) * ``` */ get matchedRoutes(): RouterRoute[]; /** * `routePath()` can retrieve the path registered within the handler * * @see {@link https://hono.dev/docs/api/request#routepath} * * @example * ```ts * app.get('/posts/:id', (c) => { * return c.json({ path: c.req.routePath }) * }) * ``` */ get routePath(): string; } type HeaderRecord = Record<string, string | string[]>; /** * Data type can be a string, ArrayBuffer, or ReadableStream. */ type Data = string | ArrayBuffer | ReadableStream; /** * Interface for the execution context in a web worker or similar environment. */ interface ExecutionContext { /** * Extends the lifetime of the event callback until the promise is settled. * * @param promise - A promise to wait for. */ waitUntil(promise: Promise<unknown>): void; /** * Allows the event to be passed through to subsequent event listeners. */ passThroughOnException(): void; } /** * Interface for context variable mapping. */ interface ContextVariableMap { } /** * Interface for context renderer. */ interface ContextRenderer { } /** * Interface representing a renderer for content. * * @interface DefaultRenderer * @param {string | Promise<string>} content - The content to be rendered, which can be either a string or a Promise resolving to a string. * @returns {Response | Promise<Response>} - The response after rendering the content, which can be either a Response or a Promise resolving to a Response. */ interface DefaultRenderer { (content: string | Promise<string>): Response | Promise<Response>; } /** * Renderer type which can either be a ContextRenderer or DefaultRenderer. */ type Renderer = ContextRenderer extends Function ? ContextRenderer : DefaultRenderer; /** * Extracts the props for the renderer. */ type PropsForRenderer = [...Required<Parameters<Renderer>>] extends [unknown, infer Props] ? Props : unknown; type Layout<T = Record<string, any>> = (props: T) => any; /** * Interface for getting context variables. * * @template E - Environment type. */ interface Get<E extends Env> { <Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]; <Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]; } /** * Interface for setting context variables. * * @template E - Environment type. */ interface Set$1<E extends Env> { <Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void; <Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void; } /** * Interface for creating a new response. */ interface NewResponse { (data: Data | null, status?: StatusCode, headers?: HeaderRecord): Response; (data: Data | null, init?: ResponseInit): Response; } /** * Interface for responding with a body. */ interface BodyRespond extends NewResponse { } /** * Interface for responding with text. * * @interface TextRespond * @template T - The type of the text content. * @template U - The type of the status code. * * @param {T} text - The text content to be included in the response. * @param {U} [status] - An optional status code for the response. * @param {HeaderRecord} [headers] - An optional record of headers to include in the response. * * @returns {Response & TypedResponse<T, U, 'text'>} - The response after rendering the text content, typed with the provided text and status code types. */ interface TextRespond { <T extends string, U extends StatusCode = StatusCode>(text: T, status?: U, headers?: HeaderRecord): Response & TypedResponse<T, U, 'text'>; <T extends string, U extends StatusCode = StatusCode>(text: T, init?: ResponseInit): Response & TypedResponse<T, U, 'text'>; } /** * Interface for responding with JSON. * * @interface JSONRespond * @template T - The type of the JSON value or simplified unknown type. * @template U - The type of the status code. * * @param {T} object - The JSON object to be included in the response. * @param {U} [status] - An optional status code for the response. * @param {HeaderRecord} [headers] - An optional record of headers to include in the response. * * @returns {JSONRespondReturn<T, U>} - The response after rendering the JSON object, typed with the provided object and status code types. */ interface JSONRespond { <T extends JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue, U extends StatusCode = StatusCode>(object: T, status?: U, headers?: HeaderRecord): JSONRespondReturn<T, U>; <T extends JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue, U extends StatusCode = StatusCode>(object: T, init?: ResponseInit): JSONRespondReturn<T, U>; } /** * @template T - The type of the JSON value or simplified unknown type. * @template U - The type of the status code. * * @returns {Response & TypedResponse<SimplifyDeepArray<T> extends JSONValue ? (JSONValue extends SimplifyDeepArray<T> ? never : JSONParsed<T>) : never, U, 'json'>} - The response after rendering the JSON object, typed with the provided object and status code types. */ type JSONRespondReturn<T extends JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue, U extends StatusCode> = Response & TypedResponse<SimplifyDeepArray<T> extends JSONValue ? JSONValue extends SimplifyDeepArray<T> ? never : JSONParsed<T> : JSONParsed<T>, U, 'json'>; /** * Interface representing a function that responds with HTML content. * * @param html - The HTML content to respond with, which can be a string or a Promise that resolves to a string. * @param status - (Optional) The HTTP status code for the response. * @param headers - (Optional) A record of headers to include in the response. * @param init - (Optional) The response initialization object. * * @returns A Response object or a Promise that resolves to a Response object. */ interface HTMLRespond { <T extends string | Promise<string>>(html: T, status?: StatusCode, headers?: HeaderRecord): T extends string ? Response : Promise<Response>; <T extends string | Promise<string>>(html: T, init?: ResponseInit): T extends string ? Response : Promise<Response>; } /** * Options for configuring the context. * * @template E - Environment type. */ type ContextOptions<E extends Env> = { /** * Bindings for the environment. */ env: E['Bindings']; /** * Execution context for the request. */ executionCtx?: FetchEventLike | ExecutionContext | undefined; /** * Handler for not found responses. */ notFoundHandler?: NotFoundHandler<E>; matchResult?: Result<[H, RouterRoute]>; path?: string; }; declare class Context<E extends Env = any, P extends string = any, I extends Input = {}> { #private; /** * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers. * * @see {@link https://hono.dev/docs/api/context#env} * * @example * ```ts * // Environment object for Cloudflare Workers * app.get('*', async c => { * const counter = c.env.COUNTER * }) * ``` */ env: E['Bindings']; finalized: boolean; /** * `.error` can get the error object from the middleware if the Handler throws an error. * * @see {@link https://hono.dev/docs/api/context#error} * * @example * ```ts * app.use('*', async (c, next) => { * await next() * if (c.error) { * // do something... * } * }) * ``` */ error: Error | undefined; /** * Creates an instance of the Context class. * * @param req - The Request object. * @param options - Optional configuration options for the context. */ constructor(req: Request, options?: ContextOptions<E>); /** * `.req` is the instance of {@link HonoRequest}. */ get req(): HonoRequest<P, I['out']>; /** * @see {@link https://hono.dev/docs/api/context#event} * The FetchEvent associated with the current request. * * @throws Will throw an error if the context does not have a FetchEvent. */ get event(): FetchEventLike; /** * @see {@link https://hono.dev/docs/api/context#executionctx} * The ExecutionContext associated with the current request. * * @throws Will throw an error if the context does not have an ExecutionContext. */ get executionCtx(): ExecutionContext; /** * @see {@link https://hono.dev/docs/api/context#res} * The Response object for the current request. */ get res(): Response; /** * Sets the Response object for the current request. * * @param _res - The Response object to set. */ set res(_res: Response | undefined); /** * `.render()` can create a response within a layout. * * @see {@link https://hono.dev/docs/api/context#render-setrenderer} * * @example * ```ts * app.get('/', (c) => { * return c.render('Hello!') * }) * ``` */ render: Renderer; /** * Sets the layout for the response. * * @param layout - The layout to set. * @returns The layout function. */ setLayout: (layout: Layout<PropsForRenderer & { Layout: Layout; }>) => Layout<PropsForRenderer & { Layout: Layout; }>; /** * Gets the current layout for the response. * * @returns The current layout function. */ getLayout: () => Layout<PropsForRenderer & { Layout: Layout; }> | undefined; /** * `.setRenderer()` can set the layout in the custom middleware. * * @see {@link https://hono.dev/docs/api/context#render-setrenderer} * * @example * ```tsx * app.use('*', async (c, next) => { * c.setRenderer((content) => { * return c.html( * <html> * <body> * <p>{content}</p> * </body> * </html> * ) * }) * await next() * }) * ``` */ setRenderer: (renderer: Renderer) => void; /** * `.header()` can set headers. * * @see {@link https://hono.dev/docs/api/context#body} * * @example * ```ts * app.get('/welcome', (c) => { * // Set headers * c.header('X-Message', 'Hello!') * c.header('Content-Type', 'text/plain') * * return c.body('Thank you for coming') * }) * ``` */ header: (name: string, value: string | undefined, options?: { append?: boolean; }) => void; status: (status: StatusCode) => void; /** * `.set()` can set the value specified by the key. * * @see {@link https://hono.dev/docs/api/context#set-get} * * @example * ```ts * app.use('*', async (c, next) => { * c.set('message', 'Hono is cool!!') * await next() * }) * ``` */ set: Set$1<IsAny<E> extends true ? { Variables: ContextVariableMap & Record<string, any>; } : E>; /** * `.get()` can use the value specified by the key. * * @see {@link https://hono.dev/docs/api/context#set-get} * * @example * ```ts * app.get('/', (c) => { * const message = c.get('message') * return c.text(`The message is "${message}"`) * }) * ``` */ get: Get<IsAny<E> extends true ? { Variables: ContextVariableMap & Record<string, any>; } : E>; /** * `.var` can access the value of a variable. * * @see {@link https://hono.dev/docs/api/context#var} * * @example * ```ts * const result = c.var.client.oneMethod() * ``` */ get var(): Readonly<ContextVariableMap & (IsAny<E['Variables']> extends true ? Record<string, any> : E['Variables'])>; newResponse: NewResponse; /** * `.body()` can return the HTTP response. * You can set headers with `.header()` and set HTTP status code with `.status`. * This can also be set in `.text()`, `.json()` and so on. * * @see {@link https://hono.dev/docs/api/context#body} * * @example * ```ts * app.get('/welcome', (c) => { * // Set headers * c.header('X-Message', 'Hello!') * c.header('Content-Type', 'text/plain') * // Set HTTP status code * c.status(201) * * // Return the response body * return c.body('Thank you for coming') * }) * ``` */ body: BodyRespond; /** * `.text()` can render text as `Content-Type:text/plain`. * * @see {@link https://hono.dev/docs/api/context#text} * * @example * ```ts * app.get('/say', (c) => { * return c.text('Hello!') * }) * ``` */ text: TextRespond; /** * `.json()` can render JSON as `Content-Type:application/json`. * * @see {@link https://hono.dev/docs/api/context#json} * * @example * ```ts * app.get('/api', (c) => { * return c.json({ message: 'Hello!' }) * }) * ``` */ json: JSONRespond; html: HTMLRespond; /** * `.redirect()` can Redirect, default status code is 302. * * @see {@link https://hono.dev/docs/api/context#redirect} * * @example * ```ts * app.get('/redirect', (c) => { * return c.redirect('/') * }) * app.get('/redirect-permanently', (c) => { * return c.redirect('/', 301) * }) * ``` */ redirect: <T extends RedirectStatusCode = 302>(location: string, status?: T | undefined) => Response & TypedResponse<undefined, T, "redirect">; /** * `.notFound()` can return the Not Found Response. * * @see {@link https://hono.dev/docs/api/context#notfound} * * @example * ```ts * app.get('/notfound', (c) => { * return c.notFound() * }) * ``` */ notFound: () => Response | Promise<Response>; } type CacheKey = QueryKey | ((ctx: Context) => QueryKey); type CacheOptions = Omit<CreateQuery, 'queryKey' | 'queryFn' | 'throwOnError' | 'revalidate'> & { cacheKey: CacheKey; handler: Handler; revalidate?: boolean | ((ctx: Context) => boolean); }; declare const cache: ({ cacheKey, handler, revalidate, ...options }: CacheOptions) => MiddlewareHandler; export { cache };