Skip to content
Myr

refactor(context): allow passing `HonoRequest` as 1st arg (#1312)

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

* perf(context): allow passing `HonoRequest` as 1st arg * denoify * test: fix the node runtime test * test: fix deno tests

authored by Yusuke Wada · committed by GitHub · parent 1a2c0d5 · Browse files · 8 files+30 added−68 removed
This commit

State

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

Diff stats

8 files+30 added−68 removed

  • tests:+18 added−14 removed
  • other:+12 added−54 removed

8 files+30 added−68 removed

modified:deno_dist/context.ts+4 added-24 removed
1import { HonoRequest } from './request.ts'1import type { HonoRequest } from './request.ts'2import { FetchEventLike } from './types.ts'3import type { Env, NotFoundHandler, Input, TypedResponse } from './types.ts'4import type { CookieOptions } from './utils/cookie.ts'5import { serialize } from './utils/cookie.ts'
69 unmodified lines
75type ContextOptions<E extends Env> = {76 env: E['Bindings']77 executionCtx?: FetchEventLike | ExecutionContext | undefined78 notFoundHandler?: NotFoundHandler<E>79 path?: string80 params?: Record<string, string>79}8081export class Context<82 // eslint-disable-next-line @typescript-eslint/no-explicit-any
1 unmodified line
84 // eslint-disable-next-line @typescript-eslint/no-explicit-any85 P extends string = any,86 I extends Input = {}87> {88 req: HonoRequest<P, I['out']>89 env: E['Bindings'] = {}90 finalized: boolean = false91 error: Error | undefined = undefined9294 // eslint-disable-next-line @typescript-eslint/no-explicit-any95 private _req?: HonoRequest<any, any>93 private _status: StatusCode = 20094 private _exCtx: FetchEventLike | ExecutionContext | undefined // _executionCtx95 private _map: Record<string, unknown> | undefined96 private _h: Headers | undefined = undefined // _headers97 private _pH: Record<string, string> | undefined = undefined // _preparedHeaders98 private _res: Response | undefined102 private _path: string = '/'103 private _params?: Record<string, string> | null99 private _init = true105 private rawRequest?: Request | null100 private notFoundHandler: NotFoundHandler<E> = () => new Response()101108 constructor(req: Request, options?: ContextOptions<E>) {109 this.rawRequest = req102 constructor(req: HonoRequest<P, I['out']>, options?: ContextOptions<E>) {103 this.req = req104 if (options) {105 this._exCtx = options.executionCtx112 this._path = options.path ?? '/'113 this._params = options.params106 this.env = options.env107 if (options.notFoundHandler) {108 this.notFoundHandler = options.notFoundHandler109 }110 }111 }112121 get req(): HonoRequest<P, I['out']> {122 if (this._req) {123 return this._req124 } else {125 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion126 this._req = new HonoRequest(this.rawRequest!, this._path, this._params!)127 this.rawRequest = undefined128 this._params = undefined129 return this._req130 }131 }132113 get event(): FetchEventLike {114 if (this._exCtx instanceof FetchEventLike) {115 return this._exCtx116 } else {
279 unmodified lines
modified:deno_dist/hono-base.ts+2 added-3 removed
1import { compose } from './compose.ts'2import { Context } from './context.ts'3import type { ExecutionContext } from './context.ts'4import { HTTPException } from './http-exception.ts'5import { HonoRequest } from './request.ts'6import type { Router } from './router.ts'7import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, METHODS } from './router.ts'8import type {9 Env,
277 unmodified lines
287 }288289 const { handlers, params } = this.matchRoute(method, path)290290 const c = new Context(request, {291 const c = new Context(new HonoRequest(request, path, params), {292 env,293 executionCtx,294 notFoundHandler: this.notFoundHandler,294 path,295 params,295 })296297 // Do not `compose` if it has only one handler298 if (handlers.length === 1) {
90 unmodified lines
modified:runtime_tests/deno/hono.test.ts+3 added-2 removed
modified:runtime_tests/node/index.test.ts+2 added-1 removed
modified:src/compose.test.ts+8 added-7 removed
1import { compose } from './compose'2import { Context } from './context'3import { HonoRequest } from './request'45type C = {6 req: Record<string, string>7 res: Record<string, string>
72 unmodified lines
8081describe('Handler and middlewares', () => {82 const middleware: Function[] = []8383 const req = new Request('http://localhost/')84 const req = new HonoRequest(new Request('http://localhost/'))85 const c: Context = new Context(req)8687 const mHandlerFoo = async (c: Context, next: Function) => {88 c.req.headers.append('x-header-foo', 'foo')
27 unmodified lines
116117describe('compose with Context - 200 success', () => {118 const middleware: Function[] = []119119 const req = new Request('http://localhost/')120 const req = new HonoRequest(new Request('http://localhost/'))121 const c: Context = new Context(req)122 const handler = (c: Context) => {123 return c.text('Hello')124 }
15 unmodified lines
140141describe('compose with Context - 404 not found', () => {142 const middleware: Function[] = []143143 const req = new Request('http://localhost/')144 const req = new HonoRequest(new Request('http://localhost/'))145 const c: Context = new Context(req)146 const onNotFound = (c: Context) => {147 return c.text('onNotFound', 404)148 }
15 unmodified lines
164165describe('compose with Context - 401 not authorized', () => {166 const middleware: Function[] = []167167 const req = new Request('http://localhost/')168 const req = new HonoRequest(new Request('http://localhost/'))169 const c: Context = new Context(req)170 const handler = (c: Context) => {171 return c.text('Hello')172 }
17 unmodified lines
190191describe('compose with Context - next() below', () => {192 const middleware: Function[] = []193193 const req = new Request('http://localhost/')194 const req = new HonoRequest(new Request('http://localhost/'))195 const c: Context = new Context(req)196 const handler = (c: Context) => {197 const message = c.req.header('x-custom') || 'blank'198 return c.text(message)
18 unmodified lines
217218describe('compose with Context - 500 error', () => {219 const middleware: Function[] = []220220 const req = new Request('http://localhost/')221 const req = new HonoRequest(new Request('http://localhost/'))222 const c: Context = new Context(req)223224 it('Error on handler', async () => {225 const handler = () => {
40 unmodified lines
266 expect(stack).toEqual([0, 1, 2])267 })268})269describe('compose with Context - not finalized', () => {269 const req = new Request('http://localhost/')270 const req = new HonoRequest(new Request('http://localhost/'))271 const c: Context = new Context(req)272 const onNotFound = (c: Context) => {273 return c.text('onNotFound', 404)274 }
386 unmodified lines
modified:src/context.test.ts+5 added-4 removed
1import { Context } from './context'2import { HonoRequest } from './request'34describe('Context', () => {4 const req = new Request('http://localhost/')5 const req = new HonoRequest(new Request('http://localhost/'))67 let c: Context8 beforeEach(() => {9 c = new Context(req)
135 unmodified lines
145 expect(await res.text()).toBe('')146 })147148 it('Should be able read env', async () => {148 const req = new Request('http://localhost/')149 const req = new HonoRequest(new Request('http://localhost/'))150 const key = 'a-secret-key'151 const ctx = new Context(req, {152 env: {153 API_KEY: key,
26 unmodified lines
180 })181})182183describe('Context header', () => {183 const req = new Request('http://localhost/')184 const req = new HonoRequest(new Request('http://localhost/'))185 let c: Context186 beforeEach(() => {187 c = new Context(req)188 })
9 unmodified lines
198 })199})200201describe('Pass a ResponseInit to respond methods', () => {201 const req = new Request('http://localhost/')202 const req = new HonoRequest(new Request('http://localhost/'))203 let c: Context204 beforeEach(() => {205 c = new Context(req)206 })
56 unmodified lines
modified:src/context.ts+4 added-24 removed
1import { HonoRequest } from './request'1import type { HonoRequest } from './request'2import { FetchEventLike } from './types'3import type { Env, NotFoundHandler, Input, TypedResponse } from './types'4import type { CookieOptions } from './utils/cookie'5import { serialize } from './utils/cookie'
69 unmodified lines
75type ContextOptions<E extends Env> = {76 env: E['Bindings']77 executionCtx?: FetchEventLike | ExecutionContext | undefined78 notFoundHandler?: NotFoundHandler<E>79 path?: string80 params?: Record<string, string>79}8081export class Context<82 // eslint-disable-next-line @typescript-eslint/no-explicit-any
1 unmodified line
84 // eslint-disable-next-line @typescript-eslint/no-explicit-any85 P extends string = any,86 I extends Input = {}87> {88 req: HonoRequest<P, I['out']>89 env: E['Bindings'] = {}90 finalized: boolean = false91 error: Error | undefined = undefined9294 // eslint-disable-next-line @typescript-eslint/no-explicit-any95 private _req?: HonoRequest<any, any>93 private _status: StatusCode = 20094 private _exCtx: FetchEventLike | ExecutionContext | undefined // _executionCtx95 private _map: Record<string, unknown> | undefined96 private _h: Headers | undefined = undefined // _headers97 private _pH: Record<string, string> | undefined = undefined // _preparedHeaders98 private _res: Response | undefined102 private _path: string = '/'103 private _params?: Record<string, string> | null99 private _init = true105 private rawRequest?: Request | null100 private notFoundHandler: NotFoundHandler<E> = () => new Response()101108 constructor(req: Request, options?: ContextOptions<E>) {109 this.rawRequest = req102 constructor(req: HonoRequest<P, I['out']>, options?: ContextOptions<E>) {103 this.req = req104 if (options) {105 this._exCtx = options.executionCtx112 this._path = options.path ?? '/'113 this._params = options.params106 this.env = options.env107 if (options.notFoundHandler) {108 this.notFoundHandler = options.notFoundHandler109 }110 }111 }112121 get req(): HonoRequest<P, I['out']> {122 if (this._req) {123 return this._req124 } else {125 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion126 this._req = new HonoRequest(this.rawRequest!, this._path, this._params!)127 this.rawRequest = undefined128 this._params = undefined129 return this._req130 }131 }132113 get event(): FetchEventLike {114 if (this._exCtx instanceof FetchEventLike) {115 return this._exCtx116 } else {
279 unmodified lines
modified:src/hono-base.ts+2 added-3 removed
1import { compose } from './compose'2import { Context } from './context'3import type { ExecutionContext } from './context'4import { HTTPException } from './http-exception'5import { HonoRequest } from './request'6import type { Router } from './router'7import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, METHODS } from './router'8import type {9 Env,
277 unmodified lines
287 }288289 const { handlers, params } = this.matchRoute(method, path)290290 const c = new Context(request, {291 const c = new Context(new HonoRequest(request, path, params), {292 env,293 executionCtx,294 notFoundHandler: this.notFoundHandler,294 path,295 params,295 })296297 // Do not `compose` if it has only one handler298 if (handlers.length === 1) {
90 unmodified lines