Skip to content
Myr

feat(types): enable adding Types for variables used in `c.set`/`c.get` (#478)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* feat(types): enable adding Types for variables used in `c.set`/`c.get` * fix typo

authored by Yusuke Wada · committed by GitHub · parent 54a04c6 · Browse files · 4 files+122 added−58 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+122 added−58 removed

  • other:+122 added−58 removed

4 files+122 added−58 removed

modified:deno_dist/context.ts+17 added-9 removed
modified:deno_dist/hono.ts+44 added-20 removed
7 unmodified lines
8import { getPathFromURL, mergePath } from './utils/url.ts'910export interface ContextVariableMap {}1112type Env = Record<string, any>13export type Handler<RequestParamKeyType extends string = string, E = Env> = (12export type Bindings = Record<string, any> // For Cloudflare Workers13export type Variables = Record<string, any> // For c.set/c.get functions14export type Environment = {15 Bindings: Bindings16 Variables: Variables17}1819export type Handler<20 RequestParamKeyType extends string = string,21 E extends Partial<Environment> = Environment22> = (23 c: Context<RequestParamKeyType, E>,24 next: Next25) => Response | Promise<Response> | Promise<void> | Promise<Response | undefined>17export type NotFoundHandler<E = Env> = (c: Context<string, E>) => Response | Promise<Response>18export type ErrorHandler<E = Env> = (err: Error, c: Context<string, E>) => Response2627export type NotFoundHandler<E extends Partial<Environment> = Environment> = (28 c: Context<string, E>29) => Response | Promise<Response>3031export type ErrorHandler<E extends Partial<Environment> = Environment> = (32 err: Error,33 c: Context<string, E>34) => Response3536export type Next = () => Promise<void>3738// eslint-disable-next-line @typescript-eslint/no-unused-vars39type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}`
7 unmodified lines
47type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`48 ? ParamKey<Component> | ParamKeys<Rest>49 : ParamKey<Path>5034interface HandlerInterface<T extends string, E extends Env = Env, U = Hono<E, T>> {51interface HandlerInterface<52 T extends string,53 E extends Partial<Environment> = Environment,54 U = Hono<E, T>55> {56 // app.get('/', handler, handler...)57 <Path extends string>(58 path: Path,59 ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, E>[]
9 unmodified lines
69const methods = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch'] as const70type Methods = typeof methods[number] | typeof METHOD_NAME_ALL_LOWERCASE7172function defineDynamicClass(): {52 new <E extends Env, T extends string, U>(): {73 new <E extends Partial<Environment> = Environment, T extends string = string, U = Hono>(): {74 [K in Methods]: HandlerInterface<T, E, U>75 }76} {77 return class {} as any78}7959interface Route<E extends Env> {80interface Route<E extends Partial<Environment> = Environment> {81 path: string82 method: string83 handler: Handler<string, E>84}8565export class Hono<E extends Env = Env, P extends string = '/'> extends defineDynamicClass()<66 E,67 P,68 Hono<E, P>69> {86export class Hono<87 E extends { Bindings?: Bindings; Variables?: Variables } = Environment,88 P extends string = '/'89> extends defineDynamicClass()<E, P, Hono<E, P>> {90 readonly router: Router<Handler<string, E>> = new TrieRouter()91 readonly strict: boolean = true // strict routing - default is true92 private _tempPath: string = ''93 private path: string = '/'
64 unmodified lines
158 })159 return this160 }161142 onError(handler: ErrorHandler<E>): Hono<E, P> {162 onError(handler: ErrorHandler): Hono<E, P> {163 this.errorHandler = handler as ErrorHandler164 return this165 }166147 notFound(handler: NotFoundHandler<E>): Hono<E, P> {148 this.notFoundHandler = handler as NotFoundHandler167 notFound(handler: NotFoundHandler): Hono<E, P> {168 this.notFoundHandler = handler169 return this170 }171172 private addRoute(method: string, path: string, handler: Handler<string, E>): void {
12 unmodified lines
185186 private async dispatch(187 request: Request,188 eventOrExecutionCtx?: ExecutionContext | FetchEvent,169 env?: E189 env?: E['Bindings']190 ): Promise<Response> {191 const path = getPathFromURL(request.url, this.strict)192 const method = request.method193
3 unmodified lines
197 const handlers = result ? result.handlers : [this.notFoundHandler]198199 const c = new HonoContext<string, E>(request, env, eventOrExecutionCtx, this.notFoundHandler)200181 const composed = compose<HonoContext>(handlers, this.errorHandler, this.notFoundHandler)182 let context: HonoContext201 const composed = compose<HonoContext<string, E>>(202 handlers,203 this.errorHandler,204 this.notFoundHandler205 )206 let context: HonoContext<string, E>207 try {208 context = await composed(c)209 if (!context.finalized) {210 throw new Error(
13 unmodified lines
224 handleEvent(event: FetchEvent): Promise<Response> {225 return this.dispatch(event.request, event)226 }227204 fetch = (request: Request, env?: E, executionCtx?: ExecutionContext) => {205 return this.dispatch(request, executionCtx, env)228 fetch = (request: Request, Environment?: E['Bindings'], executionCtx?: ExecutionContext) => {229 return this.dispatch(request, executionCtx, Environment)230 }231232 request(input: RequestInfo, requestInit?: RequestInit): Promise<Response> {233 const req = input instanceof Request ? input : new Request(input, requestInit)
3 unmodified lines
modified:src/context.ts+17 added-9 removed
1import type { ContextVariableMap, NotFoundHandler } from './hono'1import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './hono'2import type { CookieOptions } from './utils/cookie'3import { serialize } from './utils/cookie'4import type { StatusCode } from './utils/http-status'5import { isAbsoluteURL } from './utils/url'67type Headers = Record<string, string>8export type Data = string | ArrayBuffer | ReadableStream9type Env = Record<string, any>911export interface Context<RequestParamKeyType extends string = string, E = Env> {10export interface Context<11 RequestParamKeyType extends string = string,12 E extends Partial<Environment> = Environment13> {14 req: Request<RequestParamKeyType>13 env: E15 env: E['Bindings'] | Bindings16 event: FetchEvent17 executionCtx: ExecutionContext18 finalized: boolean19
2 unmodified lines
22 header: (name: string, value: string) => void23 status: (status: StatusCode) => void24 set: {25 <Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void26 <Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void27 (key: string, value: any): void28 }29 get: {30 <Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]31 <Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]32 <T = any>(key: string): T33 }34 pretty: (prettyJSON: boolean, space?: number) => void35 newResponse: (data: Data | null, status: StatusCode, headers: Headers) => Response
5 unmodified lines
41 cookie: (name: string, value: string, options?: CookieOptions) => void42 notFound: () => Response | Promise<Response>43}4441export class HonoContext<RequestParamKeyType extends string = string, E = Env>42 implements Context<RequestParamKeyType, E>45export class HonoContext<46 RequestParamKeyType extends string = string,47 E extends Partial<Environment> = Environment48> implements Context<RequestParamKeyType, E>49{50 req: Request<RequestParamKeyType>45 env: E51 env: Environment['Bindings']52 finalized: boolean5354 _status: StatusCode = 20055 private _executionCtx: FetchEvent | ExecutionContext | undefined
5 unmodified lines
61 private notFoundHandler: NotFoundHandler6263 constructor(64 req: Request,59 env: E | undefined = undefined,65 env: E['Bindings'] | undefined = undefined,66 executionCtx: FetchEvent | ExecutionContext | undefined = undefined,67 notFoundHandler: NotFoundHandler = () => new Response()68 ) {69 this._executionCtx = executionCtx70 this.req = req65 this.env = env ? env : ({} as E)71 this.env = env ? env : ({} as Bindings)7273 this.notFoundHandler = notFoundHandler74 this.finalized = false75 }
35 unmodified lines
111 this._status = status112 }113114 set<Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void115 set<Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void116 set(key: string, value: any): void117 set(key: string, value: any): void {118 this._map ||= {}119 this._map[key] = value120 }121122 get<Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]123 get<Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]124 get<T = any>(key: string): T125 get(key: string) {126 if (!this._map) {127 return undefined
64 unmodified lines
modified:src/hono.ts+44 added-20 removed
7 unmodified lines
8import { getPathFromURL, mergePath } from './utils/url'910export interface ContextVariableMap {}1112type Env = Record<string, any>13export type Handler<RequestParamKeyType extends string = string, E = Env> = (12export type Bindings = Record<string, any> // For Cloudflare Workers13export type Variables = Record<string, any> // For c.set/c.get functions14export type Environment = {15 Bindings: Bindings16 Variables: Variables17}1819export type Handler<20 RequestParamKeyType extends string = string,21 E extends Partial<Environment> = Environment22> = (23 c: Context<RequestParamKeyType, E>,24 next: Next25) => Response | Promise<Response> | Promise<void> | Promise<Response | undefined>17export type NotFoundHandler<E = Env> = (c: Context<string, E>) => Response | Promise<Response>18export type ErrorHandler<E = Env> = (err: Error, c: Context<string, E>) => Response2627export type NotFoundHandler<E extends Partial<Environment> = Environment> = (28 c: Context<string, E>29) => Response | Promise<Response>3031export type ErrorHandler<E extends Partial<Environment> = Environment> = (32 err: Error,33 c: Context<string, E>34) => Response3536export type Next = () => Promise<void>3738// eslint-disable-next-line @typescript-eslint/no-unused-vars39type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}`
7 unmodified lines
47type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`48 ? ParamKey<Component> | ParamKeys<Rest>49 : ParamKey<Path>5034interface HandlerInterface<T extends string, E extends Env = Env, U = Hono<E, T>> {51interface HandlerInterface<52 T extends string,53 E extends Partial<Environment> = Environment,54 U = Hono<E, T>55> {56 // app.get('/', handler, handler...)57 <Path extends string>(58 path: Path,59 ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, E>[]
9 unmodified lines
69const methods = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch'] as const70type Methods = typeof methods[number] | typeof METHOD_NAME_ALL_LOWERCASE7172function defineDynamicClass(): {52 new <E extends Env, T extends string, U>(): {73 new <E extends Partial<Environment> = Environment, T extends string = string, U = Hono>(): {74 [K in Methods]: HandlerInterface<T, E, U>75 }76} {77 return class {} as any78}7959interface Route<E extends Env> {80interface Route<E extends Partial<Environment> = Environment> {81 path: string82 method: string83 handler: Handler<string, E>84}8565export class Hono<E extends Env = Env, P extends string = '/'> extends defineDynamicClass()<66 E,67 P,68 Hono<E, P>69> {86export class Hono<87 E extends { Bindings?: Bindings; Variables?: Variables } = Environment,88 P extends string = '/'89> extends defineDynamicClass()<E, P, Hono<E, P>> {90 readonly router: Router<Handler<string, E>> = new TrieRouter()91 readonly strict: boolean = true // strict routing - default is true92 private _tempPath: string = ''93 private path: string = '/'
64 unmodified lines
158 })159 return this160 }161142 onError(handler: ErrorHandler<E>): Hono<E, P> {162 onError(handler: ErrorHandler): Hono<E, P> {163 this.errorHandler = handler as ErrorHandler164 return this165 }166147 notFound(handler: NotFoundHandler<E>): Hono<E, P> {148 this.notFoundHandler = handler as NotFoundHandler167 notFound(handler: NotFoundHandler): Hono<E, P> {168 this.notFoundHandler = handler169 return this170 }171172 private addRoute(method: string, path: string, handler: Handler<string, E>): void {
12 unmodified lines
185186 private async dispatch(187 request: Request,188 eventOrExecutionCtx?: ExecutionContext | FetchEvent,169 env?: E189 env?: E['Bindings']190 ): Promise<Response> {191 const path = getPathFromURL(request.url, this.strict)192 const method = request.method193
3 unmodified lines
197 const handlers = result ? result.handlers : [this.notFoundHandler]198199 const c = new HonoContext<string, E>(request, env, eventOrExecutionCtx, this.notFoundHandler)200181 const composed = compose<HonoContext>(handlers, this.errorHandler, this.notFoundHandler)182 let context: HonoContext201 const composed = compose<HonoContext<string, E>>(202 handlers,203 this.errorHandler,204 this.notFoundHandler205 )206 let context: HonoContext<string, E>207 try {208 context = await composed(c)209 if (!context.finalized) {210 throw new Error(
13 unmodified lines
224 handleEvent(event: FetchEvent): Promise<Response> {225 return this.dispatch(event.request, event)226 }227204 fetch = (request: Request, env?: E, executionCtx?: ExecutionContext) => {205 return this.dispatch(request, executionCtx, env)228 fetch = (request: Request, Environment?: E['Bindings'], executionCtx?: ExecutionContext) => {229 return this.dispatch(request, executionCtx, Environment)230 }231232 request(input: RequestInfo, requestInit?: RequestInit): Promise<Response> {233 const req = input instanceof Request ? input : new Request(input, requestInit)
3 unmodified lines