perf(context): improve initializing `Context` (#3046)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* perf(context): improve initializing `Context` * update to pass tests and CI * removed not used module * remove not used module
authored by Yusuke Wada · committed by GitHub · parent d21f8eb · Browse files · 12 files·+84 added−71 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+84 added−71 removed
- tests:+29 added−41 removed
- other:+55 added−30 removed
Provenance
- Commit
ae3a67b- Tree
ad1199d- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
d21f8eb
12 files changed+84 added−71 removed
modified:runtime_tests/deno/hono.test.ts+1 added-2 removed
1234456719 unmodified lines272829303231323334import { Context } from '../../src/context.ts'import { env, getRuntimeKey } from '../../src/helper/adapter/index.ts'import { Hono } from '../../src/hono.ts'import { HonoRequest } from '../../src/request.ts'import { assertEquals } from './deps.ts'
// Test just only minimal patterns.// Because others are tested well in Cloudflare Workers environment already.19 unmodified lines assertEquals(getRuntimeKey(), 'deno')})
Deno.test('environment variables', () => { const c = new Context(new HonoRequest(new Request('http://localhost/'))) const c = new Context(new Request('http://localhost/')) const { NAME } = env<{ NAME: string }>(c) assertEquals(NAME, 'Deno')})modified:src/adapter/bun/conninfo.test.ts+4 added-5 removed
12234514 unmodified lines20212223252425262728293031323335343536373839404142434544454647485049505152533 unmodified linesimport { Context } from '../../context'import { HonoRequest } from '../../request'import { getConnInfo } from './conninfo'
const createRandomBunServer = () => { const address = Math.random().toString()14 unmodified lines}describe('getConnInfo', () => { it('Should info is valid', () => { const { port, server, address } = createRandomBunServer() const c = new Context(new HonoRequest(new Request('http://localhost/')), { env: server }) const c = new Context(new Request('http://localhost/'), { env: server }) const info = getConnInfo(c)
expect(info.remote.port).toBe(port) expect(info.remote.address).toBe(address) expect(info.remote.addressType).toBe('IPv6') expect(info.remote.transport).toBeUndefined() }) it('Should getConnInfo works when env is { server: server }', () => { const { port, server, address } = createRandomBunServer() const c = new Context(new HonoRequest(new Request('http://localhost/')), { env: { server } }) const c = new Context(new Request('http://localhost/'), { env: { server } })
const info = getConnInfo(c)
expect(info.remote.port).toBe(port) expect(info.remote.address).toBe(address) expect(info.remote.addressType).toBe('IPv6') expect(info.remote.transport).toBeUndefined() }) it('Should throw error when user did not give server', () => { const c = new Context(new HonoRequest(new Request('http://localhost/')), { env: {} }) const c = new Context(new Request('http://localhost/'), { env: {} })
expect(() => getConnInfo(c)).toThrowError(TypeError) }) it('Should throw error when requestIP is not function', () => { const c = new Context(new HonoRequest(new Request('http://localhost/')), { const c = new Context(new Request('http://localhost/'), { env: { requestIP: 0, }, })3 unmodified linesmodified:src/adapter/bun/server.test.ts+6 added-9 removed
1223456781011121314151617910111213141516import { Context } from '../../context'import { HonoRequest } from '../../request'import { getBunServer } from './server'import type { BunServer } from './server'
describe('getBunServer', () => { it('Should success to pick Server', () => { const server = {} as BunServer
expect( getBunServer(new Context(new HonoRequest(new Request('http://localhost/')), { env: server })) ).toBe(server) expect( getBunServer( new Context(new HonoRequest(new Request('http://localhost/')), { env: { server } }) ) ).toBe(server) expect(getBunServer(new Context(new Request('http://localhost/'), { env: server }))).toBe( server ) expect(getBunServer(new Context(new Request('http://localhost/'), { env: { server } }))).toBe( server ) })})modified:src/adapter/cloudflare-workers/conninfo.test.ts+1 added-2 removed
1223452 unmodified lines8910111312131415162 unmodified linesimport { Context } from '../../context'import { HonoRequest } from '../../request'import { getConnInfo } from './conninfo'
describe('getConnInfo', () => { it('Should getConnInfo works', () => {2 unmodified lines headers: { 'cf-connecting-ip': address, }, }) const c = new Context(new HonoRequest(req)) const c = new Context(req)
const info = getConnInfo(c)
expect(info.remote.address).toBe(address)2 unmodified linesmodified:src/adapter/deno/conninfo.test.ts+1 added-2 removed
1223456781091011121311 unmodified linesimport { Context } from '../../context'import { HonoRequest } from '../../request'import { getConnInfo } from './conninfo'
describe('getConnInfo', () => { it('Should info is valid', () => { const transport = 'tcp' const address = Math.random().toString() const port = Math.floor(Math.random() * (65535 + 1)) const c = new Context(new HonoRequest(new Request('http://localhost/')), { const c = new Context(new Request('http://localhost/'), { env: { remoteAddr: { transport, hostname: address,11 unmodified linesmodified:src/helper/streaming/sse.test.ts+1 added-2 removed
1 import { Context } from '../../context'2-import { HonoRequest } from '../../request'2 import { streamSSE } from '.'3 4 describe('SSE Streaming helper', () => {6- const req = new HonoRequest(new Request('http://localhost/'))5+ const req = new Request('http://localhost/')6 let c: Context7 beforeEach(() => {8 c = new Context(req)9 })112 unmodified linesmodified:src/helper/streaming/stream.test.ts+1 added-2 removed
1 import { Context } from '../../context'2-import { HonoRequest } from '../../request'2 import { stream } from '.'3 4 describe('Basic Streaming Helper', () => {6- const req = new HonoRequest(new Request('http://localhost/'))5+ const req = new Request('http://localhost/')6 let c: Context7 beforeEach(() => {8 c = new Context(req)9 })58 unmodified linesmodified:src/helper/streaming/text.test.ts+1 added-2 removed
1223465678925 unmodified linesimport { Context } from '../../context'import { HonoRequest } from '../../request'import { streamText } from '.'
describe('Text Streaming Helper', () => { const req = new HonoRequest(new Request('http://localhost/')) const req = new Request('http://localhost/') let c: Context beforeEach(() => { c = new Context(req) })25 unmodified linesmodified:src/compose.test.ts+7 added-8 removed
1 import { compose } from './compose'2 import { Context } from './context'3-import { HonoRequest } from './request'3 import type { Params } from './router'4 5 type C = {6 req: Record<string, string>79 unmodified lines86 87 describe('Handler and middlewares', () => {88 const middleware: MiddlewareTuple[] = []89 91- const req = new HonoRequest(new Request('http://localhost/'))90+ const req = new Request('http://localhost/')91 const c: Context = new Context(req)92 93 const mHandlerFoo = async (c: Context, next: Function) => {94 c.req.raw.headers.append('x-header-foo', 'foo')27 unmodified lines122 123 describe('compose with Context - 200 success', () => {124 const middleware: MiddlewareTuple[] = []125 127- const req = new HonoRequest(new Request('http://localhost/'))126+ const req = new Request('http://localhost/')127 const c: Context = new Context(req)128 const handler = (c: Context) => {129 return c.text('Hello')130 }15 unmodified lines146 147 describe('compose with Context - 404 not found', () => {148 const middleware: MiddlewareTuple[] = []149 151- const req = new HonoRequest(new Request('http://localhost/'))150+ const req = new Request('http://localhost/')151 const onNotFound = (c: Context) => {152 return c.text('onNotFound', 404)153 }154 const onNotFoundAsync = async (c: Context) => {28 unmodified lines183 184 describe('compose with Context - 401 not authorized', () => {185 const middleware: MiddlewareTuple[] = []186 188- const req = new HonoRequest(new Request('http://localhost/'))187+ const req = new Request('http://localhost/')188 const c: Context = new Context(req)189 const handler = (c: Context) => {190 return c.text('Hello')191 }17 unmodified lines209 210 describe('compose with Context - next() below', () => {211 const middleware: MiddlewareTuple[] = []212 214- const req = new HonoRequest(new Request('http://localhost/'))213+ const req = new Request('http://localhost/')214 const c: Context = new Context(req)215 const handler = (c: Context) => {216 const message = c.req.header('x-custom') || 'blank'217 return c.text(message)18 unmodified lines236 237 describe('compose with Context - 500 error', () => {238 const middleware: MiddlewareTuple[] = []239 241- const req = new HonoRequest(new Request('http://localhost/'))240+ const req = new Request('http://localhost/')241 const c: Context = new Context(req)242 243 it('Error on handler', async () => {244 const handler = () => {56 unmodified lines301 expect(stack).toEqual([0, 1, 2])302 })303 })304 describe('compose with Context - not finalized', () => {306- const req = new HonoRequest(new Request('http://localhost/'))305+ const req = new Request('http://localhost/')306 const c: Context = new Context(req)307 const onNotFound = (c: Context) => {308 return c.text('onNotFound', 404)309 }430 unmodified linesmodified:src/context.test.ts+6 added-7 removed
1 import { Context } from './context'2 import { setCookie } from './helper/cookie'3-import { HonoRequest } from './request'3 4 describe('Context', () => {6- const req = new HonoRequest(new Request('http://localhost/'))5+ const req = new Request('http://localhost/')6 7 let c: Context8 beforeEach(() => {9 c = new Context(req)202 unmodified lines212 expect(await res.text()).toBe('')213 })214 215 it('Should be able read env', async () => {217- const req = new HonoRequest(new Request('http://localhost/'))216+ const req = new Request('http://localhost/')217 const key = 'a-secret-key'218 const ctx = new Context(req, {219 env: {220 API_KEY: key,21 unmodified lines242 })243 })244 245 describe('event and executionCtx', () => {247- const req = new HonoRequest(new Request('http://localhost/'))246+ const req = new Request('http://localhost/')247 248 it('Should return the event if accessing c.event', () => {249 const respondWith = vi.fn()250 const c = new Context(req, {36 unmodified lines287 })288 })289 290 describe('Context header', () => {292- const req = new HonoRequest(new Request('http://localhost/'))291+ const req = new Request('http://localhost/')292 let c: Context293 beforeEach(() => {294 c = new Context(req)295 })59 unmodified lines355 })356 })357 358 describe('Pass a ResponseInit to respond methods', () => {360- const req = new HonoRequest(new Request('http://localhost/'))359+ const req = new Request('http://localhost/')360 let c: Context361 beforeEach(() => {362 c = new Context(req)363 })68 unmodified lines432 }433 }434 435 describe('c.render', () => {437- const req = new HonoRequest(new Request('http://localhost/'))436+ const req = new Request('http://localhost/')437 let c: Context438 beforeEach(() => {439 c = new Context(req)440 })18 unmodified linesmodified:src/context.ts+52 added-28 removed
1-import type { HonoRequest } from './request'2-import type { Env, FetchEventLike, Input, NotFoundHandler, TypedResponse } from './types'1+import { HonoRequest } from './request'2+import type { Result } from './router'3+import type {4+ Env,5+ FetchEventLike,6+ H,7+ Input,8+ NotFoundHandler,9+ RouterRoute,10+ TypedResponse,11+} from './types'12 import { HtmlEscapedCallbackPhase, resolveCallback } from './utils/html'13 import type { RedirectStatusCode, StatusCode } from './utils/http-status'14 import type { IsAny, JSONParsed, JSONValue, SimplifyDeepArray } from './utils/types'15 195 unmodified lines211 /**212 * Handler for not found responses.213 */214 notFoundHandler?: NotFoundHandler<E>215+ matchResult?: Result<[H, RouterRoute]>216+ path?: string217 }218 219 export const TEXT_PLAIN = 'text/plain; charset=UTF-8'220 15 unmodified lines236 // eslint-disable-next-line @typescript-eslint/no-explicit-any237 P extends string = any,238 I extends Input = {}239 > {240+ #rawRequest: Request241+ #req: HonoRequest<P, I['out']> | undefined242 /**230- * `.req` is the instance of {@link HonoRequest}.231- */232- req: HonoRequest<P, I['out']>233- /**243 * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.244 *245 * @see {@link https://hono.dev/api/context#env}246 *5 unmodified lines252 * })253 * ```254 */255 env: E['Bindings'] = {}247- private _var: E['Variables'] | undefined256+ #var: E['Variables'] | undefined257 finalized: boolean = false258 /**259 * `.error` can get the error object from the middleware if the Handler throws an error.260 *8 unmodified lines269 * }270 * })271 * ```272 */264- error: Error | undefined = undefined273+ error: Error | undefined274 275 #status: StatusCode = 200276 #executionCtx: FetchEventLike | ExecutionContext | undefined268- #headers: Headers | undefined = undefined269- #preparedHeaders: Record<string, string> | undefined = undefined277+ #headers: Headers | undefined278+ #preparedHeaders: Record<string, string> | undefined279 #res: Response | undefined280 #isFresh = true272- private layout: Layout<PropsForRenderer & { Layout: Layout }> | undefined = undefined273- private renderer: Renderer = (content: string | Promise<string>) => this.html(content)274- private notFoundHandler: NotFoundHandler<E> = () => new Response()281+ #layout: Layout<PropsForRenderer & { Layout: Layout }> | undefined282+ #renderer: Renderer | undefined283+ #notFoundHandler: NotFoundHandler<E> | undefined284 285+ #matchResult: Result<[H, RouterRoute]> | undefined286+ #path: string | undefined287+288 /**289 * Creates an instance of the Context class.290 *279- * @param req - The HonoRequest object.291+ * @param req - The Request object.292 * @param options - Optional configuration options for the context.293 */282- constructor(req: HonoRequest<P, I['out']>, options?: ContextOptions<E>) {283- this.req = req294+ constructor(req: Request, options?: ContextOptions<E>) {295+ this.#rawRequest = req296 if (options) {297 this.#executionCtx = options.executionCtx298 this.env = options.env287- if (options.notFoundHandler) {288- this.notFoundHandler = options.notFoundHandler289- }299+ this.#notFoundHandler = options.notFoundHandler300+ this.#path = options.path301+ this.#matchResult = options.matchResult302 }303 }304 305 /**306+ * `.req` is the instance of {@link HonoRequest}.307+ */308+ get req(): HonoRequest<P, I['out']> {309+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult)310+ return this.#req311+ }312+313+ /**314 * @see {@link https://hono.dev/api/context#event}315 * The FetchEvent associated with the current request.316 *317 * @throws Will throw an error if the context does not have a FetchEvent.65 unmodified lines383 * return c.render('Hello!')384 * })385 * ```386 */367- render: Renderer = (...args) => this.renderer(...args)387+ render: Renderer = (...args) => {388+ this.#renderer ??= (content: string | Promise<string>) => this.html(content)389+ return this.#renderer(...args)390+ }391 392 /**393 * Sets the layout for the response.394 *5 unmodified lines400 ): Layout<401 PropsForRenderer & {402 Layout: Layout403 }381- > => (this.layout = layout)404+ > => (this.#layout = layout)405 406 /**407 * Gets the current layout for the response.408 *409 * @returns The current layout function.410 */388- getLayout = () => this.layout411+ getLayout = (): Layout<PropsForRenderer & { Layout: Layout }> | undefined => this.#layout412 413 /**414 * `.setRenderer()` can set the layout in the custom middleware.415 *15 unmodified lines431 * })432 * ```433 */434 setRenderer = (renderer: Renderer): void => {412- this.renderer = renderer435+ this.#renderer = renderer436 }437 438 /**439 * `.header()` can set headers.69 unmodified lines509 * ```510 ```511 */512 set: Set<E> = (key: string, value: unknown) => {490- this._var ??= {}491- this._var[key as string] = value513+ this.#var ??= {}514+ this.#var[key as string] = value515 }516 517 /**518 * `.get()` can use the value specified by the key.8 unmodified lines527 * })528 * ```529 */530 get: Get<E> = (key: string) => {508- return this._var ? this._var[key] : undefined531+ return this.#var ? this.#var[key] : undefined532 }533 534 /**535 * `.var` can access the value of a variable.9 unmodified lines545 get var(): Readonly<546 // eslint-disable-next-line @typescript-eslint/no-explicit-any547 ContextVariableMap & (IsAny<E['Variables']> extends true ? Record<string, any> : E['Variables'])548 > {526- return { ...this._var } as never549+ return { ...this.#var } as never550 }551 552 newResponse: NewResponse = (553 data: Data | null,218 unmodified lines772 * })773 * ```774 */775 notFound = (): Response | Promise<Response> => {776+ this.#notFoundHandler ??= () => new Response()753- return this.notFoundHandler(this)777+ return this.#notFoundHandler(this)778 }779 }modified:src/hono-base.ts+3 added-2 removed
5 unmodified lines6 /* eslint-disable @typescript-eslint/no-explicit-any */7 import { compose } from './compose'8 import { Context } from './context'9 import type { ExecutionContext } from './context'10-import { HonoRequest } from './request'10 import type { Router } from './router'11 import { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from './router'12 import type {13 Env,393 unmodified lines407 408 const path = this.getPath(request, { env })409 const matchResult = this.matchRoute(method, path)410 412- const c = new Context(new HonoRequest(request, path, matchResult), {411+ const c = new Context(request, {412+ path,413+ matchResult,414 env,415 executionCtx,416 notFoundHandler: this.notFoundHandler,417 })106 unmodified lines