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
Provenance
- Commit
ddfe07e- Tree
e0b0034- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
54a04c6
4 files changed+122 added−58 removed
modified:deno_dist/context.ts+17 added-9 removed
112345678991110111213141315161718192 unmodified lines22232425262728293031323334355 unmodified lines4142434441424546474849504551525354555 unmodified lines616263645965666768697065717273747535 unmodified lines11111211311411511611711811912012112212312412512612764 unmodified linesimport type { ContextVariableMap, NotFoundHandler } from './hono.ts'import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './hono.ts'import type { CookieOptions } from './utils/cookie.ts'import { serialize } from './utils/cookie.ts'import type { StatusCode } from './utils/http-status.ts'import { isAbsoluteURL } from './utils/url.ts'
type Headers = Record<string, string>export type Data = string | ArrayBuffer | ReadableStreamtype Env = Record<string, any>
export interface Context<RequestParamKeyType extends string = string, E = Env> {export interface Context< RequestParamKeyType extends string = string, E extends Partial<Environment> = Environment> { req: Request<RequestParamKeyType> env: E env: E['Bindings'] | Bindings event: FetchEvent executionCtx: ExecutionContext finalized: boolean
2 unmodified lines header: (name: string, value: string) => void status: (status: StatusCode) => void set: { <Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void <Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void (key: string, value: any): void } get: { <Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key] <Key extends keyof E['Variables']>(key: Key): E['Variables'][Key] <T = any>(key: string): T } pretty: (prettyJSON: boolean, space?: number) => void newResponse: (data: Data | null, status: StatusCode, headers: Headers) => Response5 unmodified lines cookie: (name: string, value: string, options?: CookieOptions) => void notFound: () => Response | Promise<Response>}
export class HonoContext<RequestParamKeyType extends string = string, E = Env> implements Context<RequestParamKeyType, E>export class HonoContext< RequestParamKeyType extends string = string, E extends Partial<Environment> = Environment> implements Context<RequestParamKeyType, E>{ req: Request<RequestParamKeyType> env: E env: Environment['Bindings'] finalized: boolean
_status: StatusCode = 200 private _executionCtx: FetchEvent | ExecutionContext | undefined5 unmodified lines private notFoundHandler: NotFoundHandler
constructor( req: Request, env: E | undefined = undefined, env: E['Bindings'] | undefined = undefined, executionCtx: FetchEvent | ExecutionContext | undefined = undefined, notFoundHandler: NotFoundHandler = () => new Response() ) { this._executionCtx = executionCtx this.req = req this.env = env ? env : ({} as E) this.env = env ? env : ({} as Bindings)
this.notFoundHandler = notFoundHandler this.finalized = false }35 unmodified lines this._status = status }
set<Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void set<Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void set(key: string, value: any): void set(key: string, value: any): void { this._map ||= {} this._map[key] = value }
get<Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key] get<Key extends keyof E['Variables']>(key: Key): E['Variables'][Key] get<T = any>(key: string): T get(key: string) { if (!this._map) { return undefined64 unmodified linesmodified:deno_dist/hono.ts+44 added-20 removed
7 unmodified lines8 import { getPathFromURL, mergePath } from './utils/url.ts'9 10 export interface ContextVariableMap {}11 12-type Env = Record<string, any>13-export type Handler<RequestParamKeyType extends string = string, E = Env> = (12+export type Bindings = Record<string, any> // For Cloudflare Workers13+export type Variables = Record<string, any> // For c.set/c.get functions14+export type Environment = {15+ Bindings: Bindings16+ Variables: Variables17+}18+19+export 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>17-export type NotFoundHandler<E = Env> = (c: Context<string, E>) => Response | Promise<Response>18-export type ErrorHandler<E = Env> = (err: Error, c: Context<string, E>) => Response26+27+export type NotFoundHandler<E extends Partial<Environment> = Environment> = (28+ c: Context<string, E>29+) => Response | Promise<Response>30+31+export type ErrorHandler<E extends Partial<Environment> = Environment> = (32+ err: Error,33+ c: Context<string, E>34+) => Response35+36 export type Next = () => Promise<void>37 38 // eslint-disable-next-line @typescript-eslint/no-unused-vars39 type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}`7 unmodified lines47 type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`48 ? ParamKey<Component> | ParamKeys<Rest>49 : ParamKey<Path>50 34-interface HandlerInterface<T extends string, E extends Env = Env, U = Hono<E, T>> {51+interface 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 lines69 const methods = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch'] as const70 type Methods = typeof methods[number] | typeof METHOD_NAME_ALL_LOWERCASE71 72 function 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 }79 59-interface Route<E extends Env> {80+interface Route<E extends Partial<Environment> = Environment> {81 path: string82 method: string83 handler: Handler<string, E>84 }85 65-export class Hono<E extends Env = Env, P extends string = '/'> extends defineDynamicClass()<66- E,67- P,68- Hono<E, P>69-> {86+export 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 lines158 })159 return this160 }161 142- onError(handler: ErrorHandler<E>): Hono<E, P> {162+ onError(handler: ErrorHandler): Hono<E, P> {163 this.errorHandler = handler as ErrorHandler164 return this165 }166 147- 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 }171 172 private addRoute(method: string, path: string, handler: Handler<string, E>): void {12 unmodified lines185 186 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 lines197 const handlers = result ? result.handlers : [this.notFoundHandler]198 199 const c = new HonoContext<string, E>(request, env, eventOrExecutionCtx, this.notFoundHandler)200 181- 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 lines224 handleEvent(event: FetchEvent): Promise<Response> {225 return this.dispatch(event.request, event)226 }227 204- 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 }231 232 request(input: RequestInfo, requestInit?: RequestInit): Promise<Response> {233 const req = input instanceof Request ? input : new Request(input, requestInit)3 unmodified linesmodified:src/context.ts+17 added-9 removed
1-import type { ContextVariableMap, NotFoundHandler } from './hono'1+import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './hono'2 import type { CookieOptions } from './utils/cookie'3 import { serialize } from './utils/cookie'4 import type { StatusCode } from './utils/http-status'5 import { isAbsoluteURL } from './utils/url'6 7 type Headers = Record<string, string>8 export type Data = string | ArrayBuffer | ReadableStream9-type Env = Record<string, any>9 11-export interface Context<RequestParamKeyType extends string = string, E = Env> {10+export 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 lines22 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) => Response5 unmodified lines41 cookie: (name: string, value: string, options?: CookieOptions) => void42 notFound: () => Response | Promise<Response>43 }44 41-export class HonoContext<RequestParamKeyType extends string = string, E = Env>42- implements Context<RequestParamKeyType, E>45+export 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: boolean53 54 _status: StatusCode = 20055 private _executionCtx: FetchEvent | ExecutionContext | undefined5 unmodified lines61 private notFoundHandler: NotFoundHandler62 63 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)72 73 this.notFoundHandler = notFoundHandler74 this.finalized = false75 }35 unmodified lines111 this._status = status112 }113 114 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 }121 122 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 undefined64 unmodified linesmodified:src/hono.ts+44 added-20 removed
7 unmodified lines8 import { getPathFromURL, mergePath } from './utils/url'9 10 export interface ContextVariableMap {}11 12-type Env = Record<string, any>13-export type Handler<RequestParamKeyType extends string = string, E = Env> = (12+export type Bindings = Record<string, any> // For Cloudflare Workers13+export type Variables = Record<string, any> // For c.set/c.get functions14+export type Environment = {15+ Bindings: Bindings16+ Variables: Variables17+}18+19+export 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>17-export type NotFoundHandler<E = Env> = (c: Context<string, E>) => Response | Promise<Response>18-export type ErrorHandler<E = Env> = (err: Error, c: Context<string, E>) => Response26+27+export type NotFoundHandler<E extends Partial<Environment> = Environment> = (28+ c: Context<string, E>29+) => Response | Promise<Response>30+31+export type ErrorHandler<E extends Partial<Environment> = Environment> = (32+ err: Error,33+ c: Context<string, E>34+) => Response35+36 export type Next = () => Promise<void>37 38 // eslint-disable-next-line @typescript-eslint/no-unused-vars39 type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}`7 unmodified lines47 type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`48 ? ParamKey<Component> | ParamKeys<Rest>49 : ParamKey<Path>50 34-interface HandlerInterface<T extends string, E extends Env = Env, U = Hono<E, T>> {51+interface 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 lines69 const methods = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch'] as const70 type Methods = typeof methods[number] | typeof METHOD_NAME_ALL_LOWERCASE71 72 function 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 }79 59-interface Route<E extends Env> {80+interface Route<E extends Partial<Environment> = Environment> {81 path: string82 method: string83 handler: Handler<string, E>84 }85 65-export class Hono<E extends Env = Env, P extends string = '/'> extends defineDynamicClass()<66- E,67- P,68- Hono<E, P>69-> {86+export 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 lines158 })159 return this160 }161 142- onError(handler: ErrorHandler<E>): Hono<E, P> {162+ onError(handler: ErrorHandler): Hono<E, P> {163 this.errorHandler = handler as ErrorHandler164 return this165 }166 147- 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 }171 172 private addRoute(method: string, path: string, handler: Handler<string, E>): void {12 unmodified lines185 186 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 lines197 const handlers = result ? result.handlers : [this.notFoundHandler]198 199 const c = new HonoContext<string, E>(request, env, eventOrExecutionCtx, this.notFoundHandler)200 181- 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 lines224 handleEvent(event: FetchEvent): Promise<Response> {225 return this.dispatch(event.request, event)226 }227 204- 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 }231 232 request(input: RequestInfo, requestInit?: RequestInit): Promise<Response> {233 const req = input instanceof Request ? input : new Request(input, requestInit)3 unmodified lines