feat: `c.res` is available before dispatching (#272)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix(router): fixed trie-router bugs * feat: `c.res` is available before dispatching
authored by Yusuke Wada · committed by GitHub · parent e692427 · Browse files · 4 files·+32 added−40 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+32 added−40 removed
- tests:+18 added−22 removed
- other:+14 added−18 removed
Provenance
- Commit
77e16dd- Tree
60505d5- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
e692427
4 files changed+32 added−40 removed
modified:src/context.test.ts+13 added-19 removed
81 unmodified lines8283848586878687888990919293929394959697989697989910010110237 unmodified lines14014114214314414514614714814915015115215315415514414514614714814915015181 unmodified lines expect(obj['hono']).toBe('great app') })
it('Has headers and status', async () => { c.header('X-Custom1', 'Message1') c.header('X-Custom2', 'Message2') c.header('x-custom1', 'Message1') c.header('x-custom2', 'Message2') c.status(200) const res = c.newResponse('this is body', { status: 201, headers: { 'X-Custom3': 'Message3', 'X-Custom2': 'Message2-Override', 'x-custom3': 'Message3', 'x-custom2': 'Message2-Override', }, }) expect(res.headers.get('X-Custom1')).toBe('Message1') expect(res.headers.get('X-Custom2')).toBe('Message2-Override') expect(res.headers.get('X-Custom3')).toBe('Message3') expect(res.headers.get('x-Custom1')).toBe('Message1') expect(res.headers.get('x-Custom2')).toBe('Message2-Override') expect(res.headers.get('x-Custom3')).toBe('Message3') expect(res.status).toBe(201) expect(await res.text()).toBe('this is body')
// res is already set.37 unmodified lines ctx.set('k-bar', { k: 'v' }) expect(ctx.get('k-bar')).toEqual({ k: 'v' }) })
it('flash status and header after return Response', async () => { const ctx = new Context(req) ctx.status(404) ctx.header('foo', 'bar') // return Response ctx.body('body')
ctx.header('foo2', 'bar2') const res = ctx.body('after') expect(res.status).toBe(200) expect(res.headers.get('foo')).toBeNull() expect(res.headers.get('foo2')).toBe('bar2') it('has res object by default', async () => { c = new Context(req) c.res.headers.append('foo', 'bar') const res = c.text('foo') expect(res.headers.get('foo')).not.toBeNull() expect(res.headers.get('foo')).toBe('bar') })})modified:src/context.ts+9 added-14 removed
10 unmodified lines11 res: Response12 env: E13 event: FetchEvent14 15- private _headers: Headers = {}15 private _status: StatusCode = 20016 private _pretty: boolean = false17 private _prettySpace: number = 218 private _map: {8 unmodified lines27 opts?: { env: E; event: FetchEvent; res?: Response }28 ) {29 this.req = this.initRequest<RequestParamKeyType>(req)30 this._map = {}31+32 Object.assign(this, opts)33 34 if (!this.res) {35 const res = new Response(null, { status: 404 })44 unmodified lines80 return req81 }82 83 header(name: string, value: string): void {84- if (this.res) {85- this.res.headers.set(name, value)84+ this.res.headers.set(name, value)86- }87- this._headers[name] = value85 }86 87 status(status: StatusCode): void {88 this._status = status13 unmodified lines102 }103 104 newResponse(data: Data, init: ResponseInit = {}): Response {105 init.status = init.status || this._status || 200109- init.headers = { ...this._headers, ...init.headers }106+ let headers: Record<string, string> = {}107+ this.res.headers.forEach((v, k) => {108+ headers[k] = v109+ })110+ init.headers = Object.assign(headers, init.headers)111+ headers = {}112 111- // Initialize112- this._status = 200113- this._headers = {}113 return new Response(data, init)114 }115 117- body(118- data: Data | null,119- status: StatusCode = this._status,120- headers: Headers = this._headers121- ): Response {116+ body(data: Data | null, status: StatusCode = this._status, headers: Headers = {}): Response {117 return this.newResponse(data, {118 status: status,119 headers: headers,120 })46 unmodified linesmodified:src/hono.test.ts+5 added-3 removed
431 unmodified lines432 describe('Basic', () => {433 const app = new Hono()434 435 app.all('*', async (c, next) => {436+ c.header('x-before-dispatch', 'foo')437 await next()438 c.header('x-custom-message', 'hello')439 })440 19 unmodified lines460 it('GET /abc', async () => {461 const res = await app.request('http://localhost/abc')462 expect(res.status).toBe(200)463 expect(res.headers.get('x-custom-message')).toBe('hello')464+ expect(res.headers.get('x-before-dispatch')).toBe('foo')465 expect(await res.text()).toBe('bar')466 })467 it('POST /abc', async () => {468 const res = await app.request('http://localhost/abc', { method: 'POST' })139 unmodified lines608 609 api.get('/posts', (c) => c.text('List'))610 api.post('/posts', (c) => c.text('Create'))611 api.get('/posts/:id', (c) => c.text(`GET ${c.req.param('id')}`))610- app.route('/api', api)612 612- app.get('/foo', (c) => c.text('bar'))613-613 middleware.use('*', async (c, next) => {614 await next()615 c.res.headers.append('x-custom-b', 'b')616 })617 618+ app.route('/api', api)619 app.route('/api', middleware)620 621+ app.get('/foo', (c) => c.text('bar'))622+623 it('Should return not found response', async () => {624 const res = await app.request('http://localhost/')625 expect(res.status).toBe(404)626 })216 unmodified linesmodified:src/hono.ts+5 added-4 removed
87 unmodified lines88 readonly strict: boolean = true // strict routing - default is true89 private _tempPath: string90 private path: string = '/'91 92- private _cacheResponse: Response92+ private _cachedResponse: Response93 94 routes: Route<E>[] = []95 96 constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {22 unmodified lines119 Object.assign(this, init)120 121 this._tempPath = null122 123- this._cacheResponse = new Response(null, { status: 404 })124- this._cacheResponse.finalized = false123+ this._cachedResponse = new Response(null, { status: 404 })124+ this._cachedResponse.finalized = false125 }126 127 private notFoundHandler: NotFoundHandler = (c: Context) => {128 const message = '404 Not Found'60 unmodified lines189 const path = getPathFromURL(request.url, { strict: this.strict })190 const method = request.method191 192 const result = await this.matchRoute(method, path)193+194 request.param = ((key?: string): string | Record<string, string> => {195 if (result) {196 if (key) {197 return result.params[key]6 unmodified lines204 205 const c = new Context<string, E>(request, {206 env: env,207 event: event,207- res: this._cacheResponse,208+ res: this._cachedResponse,209 })210 c.notFound = () => this.notFoundHandler(c)211 212 const composed = compose<Context>(handlers, this.errorHandler, this.notFoundHandler)33 unmodified lines