Skip to content
Myr

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

11 files+93 added−26 removed

modified:deno_dist/middleware/validator/middleware.ts+4 added
modified:deno_dist/utils/types.ts+7 added
modified:deno_dist/hono.ts+7 added-6 removed
80 unmodified lines
81 extendRequestPrototype()8283 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 lines
211 const handler = result.handlers[0]212 let res: ReturnType<Handler<P>>213214 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 lines
239 const composed = compose<Context<P, E>, E>(handlers, this.notFoundHandler, this.errorHandler)240241 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 lines
modified:deno_dist/request.ts+12 added-4 removed
1import { parseBody } from './utils/body.ts'2import type { BodyData } from './utils/body.ts'3import type { Cookie } from './utils/cookie.ts'4import { parse } from './utils/cookie.ts'5import type { UnionToIntersection } from './utils/types.ts'6import { getQueryStringFromURL } from './utils/url.ts'78type RemoveQuestion<T> = T extends `${infer R}?` ? R : T9// eslint-disable-next-line @typescript-eslint/no-unused-vars10type UndefinedIfHavingQuestion<T> = T extends `${infer _}?` ? string | undefined : string11type ParamKeyToRecord<T extends string> = T extends `${infer R}?`12 ? Record<R, string | undefined>13 : Record<T, string>1415declare 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): string
146 unmodified lines
modified:deno_dist/types.ts+1 added-3 removed
39 unmodified lines
40type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}`41 ? Name42 : NameWithPattern4344type ParamKey<Component> = Component extends `:${infer NameWithPattern}?`44type ParamKey<Component> = Component extends `:${infer NameWithPattern}`45 ? ParamKeyName<NameWithPattern>46 : Component extends `:${infer NameWithPattern}`47 ? ParamKeyName<NameWithPattern>46 : never4748export type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`49 ? ParamKey<Component> | ParamKeys<Rest>
30 unmodified lines
modified:src/middleware/validator/middleware.ts+4 added
40 unmodified lines
41 messages: [],42 results: [],43 }4445 // 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 lines
111 c.req.valid(data)112 }113114 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 lines
modified:src/utils/types.ts+7 added
modified:src/hono.test.ts+31 added
1385 unmodified lines
1386 app.showRoutes()1387 expect(console.log).toBeCalled()1388 })1389})13901391describe('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>>13991400 return c.json({1401 type: type,1402 })1403 })14041405 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 })14121413 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 lines
81 extendRequestPrototype()8283 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 lines
211 const handler = result.handlers[0]212 let res: ReturnType<Handler<P>>213214 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 lines
239 const composed = compose<Context<P, E>, E>(handlers, this.notFoundHandler, this.errorHandler)240241 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 lines
modified:src/request.ts+12 added-4 removed
1import { parseBody } from './utils/body'2import type { BodyData } from './utils/body'3import type { Cookie } from './utils/cookie'4import { parse } from './utils/cookie'5import type { UnionToIntersection } from './utils/types'6import { getQueryStringFromURL } from './utils/url'78type RemoveQuestion<T> = T extends `${infer R}?` ? R : T9// eslint-disable-next-line @typescript-eslint/no-unused-vars10type UndefinedIfHavingQuestion<T> = T extends `${infer _}?` ? string | undefined : string11type ParamKeyToRecord<T extends string> = T extends `${infer R}?`12 ? Record<R, string | undefined>13 : Record<T, string>1415declare 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): string
146 unmodified lines
modified:src/types.ts+1 added-3 removed
39 unmodified lines
40type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}`41 ? Name42 : NameWithPattern4344type ParamKey<Component> = Component extends `:${infer NameWithPattern}?`44type ParamKey<Component> = Component extends `:${infer NameWithPattern}`45 ? ParamKeyName<NameWithPattern>46 : Component extends `:${infer NameWithPattern}`47 ? ParamKeyName<NameWithPattern>46 : never4748export type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`49 ? ParamKey<Component> | ParamKeys<Rest>
30 unmodified lines