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
Provenance
- Commit
dc0696f- Tree
fce6b7c- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
1a2c0d5
8 files changed+30 added−68 removed
modified:deno_dist/context.ts+4 added-24 removed
1-import { HonoRequest } from './request.ts'1+import type { HonoRequest } from './request.ts'2 import { FetchEventLike } from './types.ts'3 import type { Env, NotFoundHandler, Input, TypedResponse } from './types.ts'4 import type { CookieOptions } from './utils/cookie.ts'5 import { serialize } from './utils/cookie.ts'69 unmodified lines75 type ContextOptions<E extends Env> = {76 env: E['Bindings']77 executionCtx?: FetchEventLike | ExecutionContext | undefined78 notFoundHandler?: NotFoundHandler<E>79- path?: string80- params?: Record<string, string>79 }80 81 export class Context<82 // eslint-disable-next-line @typescript-eslint/no-explicit-any1 unmodified line84 // 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 = undefined92 94- // 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()101 108- 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 }112 121- 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- }132-113 get event(): FetchEventLike {114 if (this._exCtx instanceof FetchEventLike) {115 return this._exCtx116 } else {279 unmodified linesmodified:deno_dist/hono-base.ts+2 added-3 removed
1 import { compose } from './compose.ts'2 import { Context } from './context.ts'3 import type { ExecutionContext } from './context.ts'4 import { HTTPException } from './http-exception.ts'5+import { HonoRequest } from './request.ts'6 import type { Router } from './router.ts'7 import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, METHODS } from './router.ts'8 import type {9 Env,277 unmodified lines287 }288 289 const { handlers, params } = this.matchRoute(method, path)290 290- 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 })296 297 // Do not `compose` if it has only one handler298 if (handlers.length === 1) {90 unmodified linesmodified:runtime_tests/deno/hono.test.ts+3 added-2 removed
1234567813 unmodified lines222324252526272829303031323334import { env } from '../../deno_dist/adapter.ts'import { Context } from '../../deno_dist/context.ts'import { Hono } from '../../deno_dist/mod.ts'import { HonoRequest } from '../../deno_dist/request.ts'import { assertEquals } from './deps.ts'
// Test just only minimal patterns.// Because others are tested well in Cloudflare Workers environment already.13 unmodified lines assertEquals(res.headers.get('x-query'), 'bar')})
Deno.test('runtime', () => { const c = new Context(new Request('http://localhost/')) const c = new Context(new HonoRequest(new Request('http://localhost/'))) assertEquals(c.runtime, 'deno')})
Deno.test('environment variables', () => { const c = new Context(new Request('http://localhost/')) const c = new Context(new HonoRequest(new Request('http://localhost/'))) const { NAME } = env<{ NAME: string }>(c) assertEquals(NAME, 'Deno')})modified:runtime_tests/node/index.test.ts+2 added-1 removed
3 unmodified lines45678910111223 unmodified lines3637383939404142434454 unmodified lines3 unmodified linesimport { env } from '../../src/adapter'import { Context } from '../../src/context'import { basicAuth } from '../../src/middleware/basic-auth'import { jwt } from '../../src/middleware/jwt'import { HonoRequest } from '../../src/request'
// Test only minimal patterns.// See <https://github.com/honojs/node-server> for more tests and information.
23 unmodified lines})
describe('Environment Variables', () => { it('Should return the environment variable', async () => { const c = new Context(new Request('http://localhost/')) const c = new Context(new HonoRequest(new Request('http://localhost/'))) const { NAME } = env<{ NAME: string }>(c) expect(NAME).toBe('Node') })})54 unmodified linesmodified:src/compose.test.ts+8 added-7 removed
1 import { compose } from './compose'2 import { Context } from './context'3+import { HonoRequest } from './request'4 5 type C = {6 req: Record<string, string>7 res: Record<string, string>72 unmodified lines80 81 describe('Handler and middlewares', () => {82 const middleware: Function[] = []83 83- const req = new Request('http://localhost/')84+ const req = new HonoRequest(new Request('http://localhost/'))85 const c: Context = new Context(req)86 87 const mHandlerFoo = async (c: Context, next: Function) => {88 c.req.headers.append('x-header-foo', 'foo')27 unmodified lines116 117 describe('compose with Context - 200 success', () => {118 const middleware: Function[] = []119 119- 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 lines140 141 describe('compose with Context - 404 not found', () => {142 const middleware: Function[] = []143 143- 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 lines164 165 describe('compose with Context - 401 not authorized', () => {166 const middleware: Function[] = []167 167- 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 lines190 191 describe('compose with Context - next() below', () => {192 const middleware: Function[] = []193 193- 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 lines217 218 describe('compose with Context - 500 error', () => {219 const middleware: Function[] = []220 220- const req = new Request('http://localhost/')221+ const req = new HonoRequest(new Request('http://localhost/'))222 const c: Context = new Context(req)223 224 it('Error on handler', async () => {225 const handler = () => {40 unmodified lines266 expect(stack).toEqual([0, 1, 2])267 })268 })269 describe('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 linesmodified:src/context.test.ts+5 added-4 removed
1 import { Context } from './context'2+import { HonoRequest } from './request'3 4 describe('Context', () => {4- const req = new Request('http://localhost/')5+ const req = new HonoRequest(new Request('http://localhost/'))6 7 let c: Context8 beforeEach(() => {9 c = new Context(req)135 unmodified lines145 expect(await res.text()).toBe('')146 })147 148 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 lines180 })181 })182 183 describe('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 lines198 })199 })200 201 describe('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 linesmodified:src/context.ts+4 added-24 removed
1-import { HonoRequest } from './request'1+import type { HonoRequest } from './request'2 import { FetchEventLike } from './types'3 import type { Env, NotFoundHandler, Input, TypedResponse } from './types'4 import type { CookieOptions } from './utils/cookie'5 import { serialize } from './utils/cookie'69 unmodified lines75 type ContextOptions<E extends Env> = {76 env: E['Bindings']77 executionCtx?: FetchEventLike | ExecutionContext | undefined78 notFoundHandler?: NotFoundHandler<E>79- path?: string80- params?: Record<string, string>79 }80 81 export class Context<82 // eslint-disable-next-line @typescript-eslint/no-explicit-any1 unmodified line84 // 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 = undefined92 94- // 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()101 108- 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 }112 121- 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- }132-113 get event(): FetchEventLike {114 if (this._exCtx instanceof FetchEventLike) {115 return this._exCtx116 } else {279 unmodified linesmodified:src/hono-base.ts+2 added-3 removed
1 import { compose } from './compose'2 import { Context } from './context'3 import type { ExecutionContext } from './context'4 import { HTTPException } from './http-exception'5+import { HonoRequest } from './request'6 import type { Router } from './router'7 import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, METHODS } from './router'8 import type {9 Env,277 unmodified lines287 }288 289 const { handlers, params } = this.matchRoute(method, path)290 290- 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 })296 297 // Do not `compose` if it has only one handler298 if (handlers.length === 1) {90 unmodified lines