fix(request): make optional param type correct (#826)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix(request): make optional param type correct * `ts-ignore` * `denoify`
authored by Yusuke Wada · committed by GitHub · parent 8dfdba9 · Browse files · 11 files·+93 added−26 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+93 added−26 removed
- tests:+31 added−0 removed
- other:+62 added−26 removed
Provenance
- Commit
a60e46a- Tree
2672fbd- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
8dfdba9
11 files changed+93 added−26 removed
modified:deno_dist/middleware/validator/middleware.ts+4 added
40 unmodified lines4142434445464748495060 unmodified lines11111211311411511611711811912042 unmodified lines40 unmodified lines messages: [], results: [], }
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const schema = validationFunction(v, c) const validatorList = getValidatorList(schema) // eslint-disable-next-line @typescript-eslint/no-explicit-any let data: any = {}60 unmodified lines c.req.valid(data) }
if (options && options.done) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const res = options.done(resultSet, c) if (res) { return res }42 unmodified linesmodified:deno_dist/utils/types.ts+7 added
123456789101112/* eslint-disable @typescript-eslint/no-explicit-any */export type Expect<T extends true> = Texport type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? true : falseexport type NotEqual<X, Y> = true extends Equal<X, Y> ? false : true
export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ( k: infer I) => void ? I : nevermodified:deno_dist/hono.ts+7 added-6 removed
80 unmodified lines81 extendRequestPrototype()82 83 const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]84 allMethods.map((method) => {85- this[method] = <Env extends Environment, Data>(86- args1: string | Handler<string, Env, Data>,87- ...args: Handler<string, Env, Data>[]88- ) => {85+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment86+ // @ts-ignore87+ this[method] = (args1: string | Handler, ...args: Handler[]) => {88 if (typeof args1 === 'string') {89 this.path = args190 } else {91 this.addRoute(method, this.path, args1 as unknown as Handler<P, E, S>)119 unmodified lines211 const handler = result.handlers[0]212 let res: ReturnType<Handler<P>>213 214 try {216- res = handler(c as unknown as Context<string, E, S>, async () => {})215+ // eslint-disable-next-line @typescript-eslint/no-explicit-any216+ res = handler(c as any, async () => {})217 if (!res) return this.notFoundHandler(c)218 } catch (err) {219 return this.handleError(err, c)220 }18 unmodified lines239 const composed = compose<Context<P, E>, E>(handlers, this.notFoundHandler, this.errorHandler)240 241 return (async () => {242 try {243+ // eslint-disable-next-line @typescript-eslint/no-explicit-any243- const tmp = composed(c)244+ const tmp = composed(c as any)245 const context = tmp instanceof Promise ? await tmp : tmp246 if (!context.finalized) {247 throw new Error(248 'Context is not finalized. You may forget returning Response object or `await next()`'22 unmodified linesmodified:deno_dist/request.ts+12 added-4 removed
1 import { parseBody } from './utils/body.ts'2 import type { BodyData } from './utils/body.ts'3 import type { Cookie } from './utils/cookie.ts'4 import { parse } from './utils/cookie.ts'5+import type { UnionToIntersection } from './utils/types.ts'6 import { getQueryStringFromURL } from './utils/url.ts'7 8+type RemoveQuestion<T> = T extends `${infer R}?` ? R : T9+// eslint-disable-next-line @typescript-eslint/no-unused-vars10+type UndefinedIfHavingQuestion<T> = T extends `${infer _}?` ? string | undefined : string11+type ParamKeyToRecord<T extends string> = T extends `${infer R}?`12+ ? Record<R, string | undefined>13+ : Record<T, string>14+15 declare global {16 interface Request<17 // eslint-disable-next-line @typescript-eslint/no-unused-vars18 CfHostMetadata = unknown,11- ParamKeyType extends string = string,19+ ParamKey extends string = string,20 // eslint-disable-next-line @typescript-eslint/no-explicit-any21 Data = any22 > {15- paramData?: Record<ParamKeyType, string>23+ paramData?: Record<ParamKey, string>24 param: {17- (key: ParamKeyType): string18- (): Record<ParamKeyType, string>25+ (key: RemoveQuestion<ParamKey>): UndefinedIfHavingQuestion<ParamKey>26+ (): UnionToIntersection<ParamKeyToRecord<ParamKey>>27 }28 queryData?: Record<string, string>29 query: {30 (key: string): string146 unmodified linesmodified:deno_dist/types.ts+1 added-3 removed
39 unmodified lines40 type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}`41 ? Name42 : NameWithPattern43 44-type ParamKey<Component> = Component extends `:${infer NameWithPattern}?`44+type ParamKey<Component> = Component extends `:${infer NameWithPattern}`45 ? ParamKeyName<NameWithPattern>46- : Component extends `:${infer NameWithPattern}`47- ? ParamKeyName<NameWithPattern>46 : never47 48 export type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`49 ? ParamKey<Component> | ParamKeys<Rest>30 unmodified linesmodified:src/middleware/validator/middleware.ts+4 added
40 unmodified lines41 messages: [],42 results: [],43 }44 45+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment46+ // @ts-ignore47 const schema = validationFunction(v, c)48 const validatorList = getValidatorList(schema)49 // eslint-disable-next-line @typescript-eslint/no-explicit-any50 let data: any = {}60 unmodified lines111 c.req.valid(data)112 }113 114 if (options && options.done) {115+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment116+ // @ts-ignore117 const res = options.done(resultSet, c)118 if (res) {119 return res120 }42 unmodified linesmodified:src/utils/types.ts+7 added
123456789101112/* eslint-disable @typescript-eslint/no-explicit-any */export type Expect<T extends true> = Texport type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? true : falseexport type NotEqual<X, Y> = true extends Equal<X, Y> ? false : true
export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ( k: infer I) => void ? I : nevermodified:src/hono.test.ts+31 added
1385 unmodified lines1386 app.showRoutes()1387 expect(console.log).toBeCalled()1388 })1389 })1390+1391+describe('Optional parameters', () => {1392+ const app = new Hono()1393+ app.get('/api/:version/animal/:type?', (c) => {1394+ const type1 = c.req.param('type')1395+ type verify = Expect<Equal<typeof type1, string | undefined>>1396+ const { type, version } = c.req.param()1397+ type verify2 = Expect<Equal<typeof version, string>>1398+ type verify3 = Expect<Equal<typeof type, string | undefined>>1399+1400+ return c.json({1401+ type: type,1402+ })1403+ })1404+1405+ it('Should match with an optional parameter', async () => {1406+ const res = await app.request('http://localhost/api/v1/animal/bird')1407+ expect(res.status).toBe(200)1408+ expect(await res.json()).toEqual({1409+ type: 'bird',1410+ })1411+ })1412+1413+ it('Should match without an optional parameter', async () => {1414+ const res = await app.request('http://localhost/api/v1/animal')1415+ expect(res.status).toBe(200)1416+ expect(await res.json()).toEqual({1417+ type: undefined,1418+ })1419+ })1420+})modified:src/hono.ts+7 added-6 removed
80 unmodified lines81 extendRequestPrototype()82 83 const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]84 allMethods.map((method) => {85- this[method] = <Env extends Environment, Data>(86- args1: string | Handler<string, Env, Data>,87- ...args: Handler<string, Env, Data>[]88- ) => {85+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment86+ // @ts-ignore87+ this[method] = (args1: string | Handler, ...args: Handler[]) => {88 if (typeof args1 === 'string') {89 this.path = args190 } else {91 this.addRoute(method, this.path, args1 as unknown as Handler<P, E, S>)119 unmodified lines211 const handler = result.handlers[0]212 let res: ReturnType<Handler<P>>213 214 try {216- res = handler(c as unknown as Context<string, E, S>, async () => {})215+ // eslint-disable-next-line @typescript-eslint/no-explicit-any216+ res = handler(c as any, async () => {})217 if (!res) return this.notFoundHandler(c)218 } catch (err) {219 return this.handleError(err, c)220 }18 unmodified lines239 const composed = compose<Context<P, E>, E>(handlers, this.notFoundHandler, this.errorHandler)240 241 return (async () => {242 try {243+ // eslint-disable-next-line @typescript-eslint/no-explicit-any243- const tmp = composed(c)244+ const tmp = composed(c as any)245 const context = tmp instanceof Promise ? await tmp : tmp246 if (!context.finalized) {247 throw new Error(248 'Context is not finalized. You may forget returning Response object or `await next()`'22 unmodified linesmodified:src/request.ts+12 added-4 removed
1 import { parseBody } from './utils/body'2 import type { BodyData } from './utils/body'3 import type { Cookie } from './utils/cookie'4 import { parse } from './utils/cookie'5+import type { UnionToIntersection } from './utils/types'6 import { getQueryStringFromURL } from './utils/url'7 8+type RemoveQuestion<T> = T extends `${infer R}?` ? R : T9+// eslint-disable-next-line @typescript-eslint/no-unused-vars10+type UndefinedIfHavingQuestion<T> = T extends `${infer _}?` ? string | undefined : string11+type ParamKeyToRecord<T extends string> = T extends `${infer R}?`12+ ? Record<R, string | undefined>13+ : Record<T, string>14+15 declare global {16 interface Request<17 // eslint-disable-next-line @typescript-eslint/no-unused-vars18 CfHostMetadata = unknown,11- ParamKeyType extends string = string,19+ ParamKey extends string = string,20 // eslint-disable-next-line @typescript-eslint/no-explicit-any21 Data = any22 > {15- paramData?: Record<ParamKeyType, string>23+ paramData?: Record<ParamKey, string>24 param: {17- (key: ParamKeyType): string18- (): Record<ParamKeyType, string>25+ (key: RemoveQuestion<ParamKey>): UndefinedIfHavingQuestion<ParamKey>26+ (): UnionToIntersection<ParamKeyToRecord<ParamKey>>27 }28 queryData?: Record<string, string>29 query: {30 (key: string): string146 unmodified linesmodified:src/types.ts+1 added-3 removed
39 unmodified lines40 type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}`41 ? Name42 : NameWithPattern43 44-type ParamKey<Component> = Component extends `:${infer NameWithPattern}?`44+type ParamKey<Component> = Component extends `:${infer NameWithPattern}`45 ? ParamKeyName<NameWithPattern>46- : Component extends `:${infer NameWithPattern}`47- ? ParamKeyName<NameWithPattern>46 : never47 48 export type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`49 ? ParamKey<Component> | ParamKeys<Rest>30 unmodified lines