Skip to content
Myr

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

12 files+84 added−71 removed

modified:runtime_tests/deno/hono.test.ts+1 added-2 removed
modified:src/adapter/bun/conninfo.test.ts+4 added-5 removed
modified:src/adapter/bun/server.test.ts+6 added-9 removed
modified:src/adapter/cloudflare-workers/conninfo.test.ts+1 added-2 removed
modified:src/adapter/deno/conninfo.test.ts+1 added-2 removed
modified:src/helper/streaming/sse.test.ts+1 added-2 removed
1import { Context } from '../../context'2import { HonoRequest } from '../../request'2import { streamSSE } from '.'34describe('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 lines
modified:src/helper/streaming/stream.test.ts+1 added-2 removed
1import { Context } from '../../context'2import { HonoRequest } from '../../request'2import { stream } from '.'34describe('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 lines
modified:src/helper/streaming/text.test.ts+1 added-2 removed
modified:src/compose.test.ts+7 added-8 removed
1import { compose } from './compose'2import { Context } from './context'3import { HonoRequest } from './request'3import type { Params } from './router'45type C = {6 req: Record<string, string>
79 unmodified lines
8687describe('Handler and middlewares', () => {88 const middleware: MiddlewareTuple[] = []8991 const req = new HonoRequest(new Request('http://localhost/'))90 const req = new Request('http://localhost/')91 const c: Context = new Context(req)9293 const mHandlerFoo = async (c: Context, next: Function) => {94 c.req.raw.headers.append('x-header-foo', 'foo')
27 unmodified lines
122123describe('compose with Context - 200 success', () => {124 const middleware: MiddlewareTuple[] = []125127 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 lines
146147describe('compose with Context - 404 not found', () => {148 const middleware: MiddlewareTuple[] = []149151 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 lines
183184describe('compose with Context - 401 not authorized', () => {185 const middleware: MiddlewareTuple[] = []186188 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 lines
209210describe('compose with Context - next() below', () => {211 const middleware: MiddlewareTuple[] = []212214 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 lines
236237describe('compose with Context - 500 error', () => {238 const middleware: MiddlewareTuple[] = []239241 const req = new HonoRequest(new Request('http://localhost/'))240 const req = new Request('http://localhost/')241 const c: Context = new Context(req)242243 it('Error on handler', async () => {244 const handler = () => {
56 unmodified lines
301 expect(stack).toEqual([0, 1, 2])302 })303})304describe('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 lines
modified:src/context.test.ts+6 added-7 removed
1import { Context } from './context'2import { setCookie } from './helper/cookie'3import { HonoRequest } from './request'34describe('Context', () => {6 const req = new HonoRequest(new Request('http://localhost/'))5 const req = new Request('http://localhost/')67 let c: Context8 beforeEach(() => {9 c = new Context(req)
202 unmodified lines
212 expect(await res.text()).toBe('')213 })214215 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 lines
242 })243})244245describe('event and executionCtx', () => {247 const req = new HonoRequest(new Request('http://localhost/'))246 const req = new Request('http://localhost/')247248 it('Should return the event if accessing c.event', () => {249 const respondWith = vi.fn()250 const c = new Context(req, {
36 unmodified lines
287 })288})289290describe('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 lines
355 })356})357358describe('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 lines
432 }433}434435describe('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 lines
modified:src/context.ts+52 added-28 removed
1import type { HonoRequest } from './request'2import type { Env, FetchEventLike, Input, NotFoundHandler, TypedResponse } from './types'1import { HonoRequest } from './request'2import type { Result } from './router'3import type {4 Env,5 FetchEventLike,6 H,7 Input,8 NotFoundHandler,9 RouterRoute,10 TypedResponse,11} from './types'12import { HtmlEscapedCallbackPhase, resolveCallback } from './utils/html'13import type { RedirectStatusCode, StatusCode } from './utils/http-status'14import type { IsAny, JSONParsed, JSONValue, SimplifyDeepArray } from './utils/types'15
195 unmodified lines
211 /**212 * Handler for not found responses.213 */214 notFoundHandler?: NotFoundHandler<E>215 matchResult?: Result<[H, RouterRoute]>216 path?: string217}218219export const TEXT_PLAIN = 'text/plain; charset=UTF-8'220
15 unmodified lines
236 // 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 lines
252 * })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 lines
269 * }270 * })271 * ```272 */264 error: Error | undefined = undefined273 error: Error | undefined274275 #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> | undefined284285 #matchResult: Result<[H, RouterRoute]> | undefined286 #path: string | undefined287288 /**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 }304305 /**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 }312313 /**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 lines
383 * 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 }391392 /**393 * Sets the layout for the response.394 *
5 unmodified lines
400 ): Layout<401 PropsForRenderer & {402 Layout: Layout403 }381 > => (this.layout = layout)404 > => (this.#layout = layout)405406 /**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.#layout412413 /**414 * `.setRenderer()` can set the layout in the custom middleware.415 *
15 unmodified lines
431 * })432 * ```433 */434 setRenderer = (renderer: Renderer): void => {412 this.renderer = renderer435 this.#renderer = renderer436 }437438 /**439 * `.header()` can set headers.
69 unmodified lines
509 * ```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 }516517 /**518 * `.get()` can use the value specified by the key.
8 unmodified lines
527 * })528 * ```529 */530 get: Get<E> = (key: string) => {508 return this._var ? this._var[key] : undefined531 return this.#var ? this.#var[key] : undefined532 }533534 /**535 * `.var` can access the value of a variable.
9 unmodified lines
545 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 }551552 newResponse: NewResponse = (553 data: Data | null,
218 unmodified lines
772 * })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 lines
6/* eslint-disable @typescript-eslint/no-explicit-any */7import { compose } from './compose'8import { Context } from './context'9import type { ExecutionContext } from './context'10import { HonoRequest } from './request'10import type { Router } from './router'11import { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from './router'12import type {13 Env,
393 unmodified lines
407408 const path = this.getPath(request, { env })409 const matchResult = this.matchRoute(method, path)410412 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