refactor: make `HonoRequest` (#330)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* refactor: make `HonoRequest` * apply to middlewares * fix tests
authored by Yusuke Wada · committed by GitHub · parent 34aa124 · Browse files · 7 files·+55 added−52 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+55 added−52 removed
- tests:+5 added−6 removed
- other:+50 added−46 removed
Provenance
- Commit
5125c78- Tree
9700a45- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
34aa124
7 files changed+55 added−52 removed
modified:src/middleware/body-parse/index.test.ts+5 added-3 removed
123456718 unmodified lines262728292830313233345 unmodified lines404142434244454647488 unmodified lines575859605961626364import { Hono } from '../../hono'import type { HonoRequest } from '../../request'import { extendHonoRequest } from '../../request'import { bodyParse } from '.'
describe('Parse Body Middleware', () => { const app = new Hono()18 unmodified lines }) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(req.parsedBody).toEqual(payload) expect(extendHonoRequest(req as HonoRequest).parsedBody).toEqual(payload) expect(await res.json()).toEqual(payload) })
it('POST with text', async () => {5 unmodified lines }) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(req.parsedBody).toEqual(payload) expect(extendHonoRequest(req as HonoRequest).parsedBody).toEqual(payload) expect(await res.text()).toEqual(payload) })
it('POST with form', async () => {8 unmodified lines }) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(req.parsedBody).toEqual({ message: 'hello' }) expect(extendHonoRequest(req as HonoRequest).parsedBody).toEqual({ message: 'hello' }) expect(await res.json()).toEqual({ message: 'hello' }) })})modified:src/middleware/body-parse/index.ts+2 added-2 removed
12345656789106 unmodified linesimport type { Context } from '../../context'import type { Next } from '../../hono'import { parseBody } from '../../utils/body'
declare global { interface Request {declare module '../../request' { interface HonoRequest { parsedBody: any }}
6 unmodified linesmodified:src/middleware/cookie/index.ts+2 added-2 removed
1234545678985 unmodified linesimport type { Context } from '../../context'import type { Next } from '../../hono'
declare global { interface Request {declare module '../../request' { interface HonoRequest { cookie: { (name: string): string (): Record<string, string> }85 unmodified linesmodified:src/compose.test.ts-3 removed
1 import { compose } from './compose'2 import { Context } from './context'3-import { extendRequestPrototype } from './request'3 5-extendRequestPrototype()6-4 type C = {5 req: Record<string, string>6 res: Record<string, string>7 }666 unmodified linesmodified:src/context.ts+9 added-3 removed
1 import type { NotFoundHandler } from './hono'2+import { extendHonoRequest } from './request'3+import type { HonoRequest } from './request'4 import type { StatusCode } from './utils/http-status'5 import { isAbsoluteURL } from './utils/url'6 7 type Headers = Record<string, string>1 unmodified line9 10 export type Env = Record<string, any>11 12 export class Context<RequestParamKeyType extends string = string, E = Env> {11- req: Request<RequestParamKeyType>13+ req: HonoRequest<RequestParamKeyType>14 env: E15 event: FetchEvent | undefined16 executionCtx: ExecutionContext | undefined17 finalized: boolean8 unmodified lines26 27 render: (content: string, params?: object, options?: object) => Response | Promise<Response>28 29 constructor(28- req: Request<RequestParamKeyType>,30+ req: HonoRequest | Request,31 env: E | undefined = undefined,32 eventOrExecutionCtx: FetchEvent | ExecutionContext | undefined = undefined,33 notFoundHandler: NotFoundHandler = () => new Response()34 ) {35+ if (req instanceof Request) {36+ this.req = extendHonoRequest(req as HonoRequest)37+ } else {33- this.req = req38+ this.req = req39+ }40 41 if (env) {42 this.env = env43 }99 unmodified linesmodified:src/hono.ts+9 added-6 removed
1 import { compose } from './compose'2 import { Context } from './context'3 import type { Env } from './context'4-import { extendRequestPrototype } from './request'4+import type { HonoRequest } from './request'5+import { extendHonoRequest } from './request'6 import type { Router } from './router'7 import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from './router'8 import { TrieRouter } from './router/trie-router' // Default Router9 import { getPathFromURL, mergePath } from './utils/url'64 unmodified lines74 75 constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {76 super()77 77- extendRequestPrototype() // FIXME: should be executed at a better timing78-78 const allMethods = [...methods, METHOD_NAME_ALL_LOWERCASE]79 allMethods.map((method) => {80 this[method] = <Path extends string = ''>(81 args1: Path | Handler<ParamKeys<Path>, E>,76 unmodified lines158 private matchRoute(method: string, path: string) {159 return this.router.match(method, path)160 }161 163- private async dispatch(request: Request, executionCtx?: ExecutionContext, env?: E): Promise<Response> {162+ private async dispatch(163+ request: Request,164+ executionCtx?: ExecutionContext,165+ env?: E166+ ): Promise<Response> {167+ request = extendHonoRequest(request as HonoRequest)168 const path = getPathFromURL(request.url, this.strict)169 const method = request.method170 171 const result = this.matchRoute(method, path)172+ ;(request as HonoRequest).paramData = result?.params173 169- request.paramData = result?.params170-174 const handlers = result ? result.handlers : [this.notFoundHandler]175 176 const c = new Context<string, E>(request, env, executionCtx, this.notFoundHandler)177 38 unmodified linesmodified:src/request.ts+28 added-33 removed
1-declare global {2- interface Request<ParamKeyType extends string = string> {3- param: {4- (key: ParamKeyType): string5- (): Record<ParamKeyType, string>1+export class HonoRequest<ParamKeyType extends string = string> extends Request {2+ param: {3+ (key: ParamKeyType): string4+ (): Record<ParamKeyType, string>6- }7- paramData?: Record<ParamKeyType, string>8- query: {9- (key: string): string10- (): Record<string, string>11- }12- queries: {13- (key: string): string[]14- (): Record<string, string[]>15- }16- header: {17- (name: string): string18- (): Record<string, string>19- }5 }6+ paramData?: Record<ParamKeyType, string>7+ query: {8+ (key: string): string9+ (): Record<string, string>10+ }11+ queries: {12+ (key: string): string[]13+ (): Record<string, string[]>14+ }15+ header: {16+ (name: string): string17+ (): Record<string, string>18+ }19 }20 23-export function extendRequestPrototype() {24- if (!!Request.prototype.param as boolean) {25- // already extended26- return27- }28-29- Request.prototype.param = function (this: Request, key?: string) {21+export function extendHonoRequest(request: HonoRequest): HonoRequest {22+ request.param = function (this: HonoRequest, key?: string) {23 if (this.paramData) {24 if (key) {25 return this.paramData[key]26 } else {27 return this.paramData28 }29 }30 return null38- } as InstanceType<typeof Request>['param']31+ } as InstanceType<typeof HonoRequest>['param']32 40- Request.prototype.header = function (this: Request, name?: string) {33+ request.header = function (this: HonoRequest, name?: string) {34 if (name) {35 return this.headers.get(name)36 } else {37 const result: Record<string, string> = {}1 unmodified line39 result[key] = value40 }41 return result42 }50- } as InstanceType<typeof Request>['header']43+ } as InstanceType<typeof HonoRequest>['header']44 52- Request.prototype.query = function (this: Request, key?: string) {45+ request.query = function (this: HonoRequest, key?: string) {46 const url = new URL(this.url)47 if (key) {48 return url.searchParams.get(key)49 } else {2 unmodified lines52 result[key] = url.searchParams.get(key) || ''53 }54 return result55 }63- } as InstanceType<typeof Request>['query']56+ } as InstanceType<typeof HonoRequest>['query']57 65- Request.prototype.queries = function (this: Request, key?: string) {58+ request.queries = function (this: HonoRequest, key?: string) {59 const url = new URL(this.url)60 if (key) {61 return url.searchParams.getAll(key)62 } else {2 unmodified lines65 result[key] = url.searchParams.getAll(key)66 }67 return result68 }76- } as InstanceType<typeof Request>['queries']69+ } as InstanceType<typeof HonoRequest>['queries']70+71+ return request72 }