Skip to content
Myr

request.test.ts

This file

Path

src/request.test.ts

567 lines 路 17.4 KiB 路 TypeScript

Last changed by

fix(request): remove `parseBody` from bodyCache to prevent TypeError (#4807)Yusuke Wadabefore adoption8bd9ddd

History of this file

Take it

1import { HTTPException } from './http-exception'2import { cloneRawRequest, HonoRequest } from './request'3import type { RouterRoute } from './types'45type RecursiveRecord<K extends string, T> = {6  [key in K]: T | RecursiveRecord<K, T>7}89describe('Query', () => {10  test('req.query() and req.queries()', () => {11    const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')12    const req = new HonoRequest(rawRequest)1314    const page = req.query('page')15    expect(page).not.toBeUndefined()16    expect(page).toBe('2')1718    const q = req.query('q')19    expect(q).toBeUndefined()2021    const tags = req.queries('tag')22    expect(tags).not.toBeUndefined()23    expect(tags).toEqual(['A', 'B'])2425    const q2 = req.queries('q2')26    expect(q2).toBeUndefined()27  })2829  test('decode special chars', () => {30    const rawRequest = new Request('http://localhost?mail=framework%40hono.dev&tag=%401&tag=%402')31    const req = new HonoRequest(rawRequest)3233    const mail = req.query('mail')34    expect(mail).toBe('framework@hono.dev')3536    const tags = req.queries('tag')37    expect(tags).toEqual(['@1', '@2'])38  })39})4041describe('Param', () => {42  test('req.param() should return empty string for zero-length match', () => {43    // Simulate a route like '/:remaining{.*}' matching '/'44    const rawRequest = new Request('http://localhost/')45    const req = new HonoRequest<'/:remaining{.*}'>(rawRequest, '/', [46      [[[undefined, {} as RouterRoute], { remaining: 0 }]],47      [''], // ParamStash with empty string for remaining48    ])4950    // Single param access should be empty string, not undefined51    expect(req.param('remaining')).toBe('')5253    // All params should include key with empty string value54    const all = req.param()55    expect(all).toEqual({ remaining: '' })56  })57  test('req.param() with ParamStash', () => {58    const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')59    const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [60      [61        [[undefined, {} as RouterRoute], { id: 0 }],62        [[undefined, {} as RouterRoute], { id: 0, name: 1 }],63      ],64      ['123', 'key'],65    ])6667    expect(req.param('id')).toBe('123')68    expect(req.param('name')).toBe(undefined)6970    req.routeIndex = 171    expect(req.param('id')).toBe('123')72    expect(req.param('name')).toBe('key')73  })7475  test('req.param() without ParamStash', () => {76    const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')77    const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [78      [79        [[undefined, {} as RouterRoute], { id: '123' }],80        [[undefined, {} as RouterRoute], { id: '456', name: 'key' }],81      ],82    ])8384    expect(req.param('id')).toBe('123')85    expect(req.param('name')).toBe(undefined)8687    req.routeIndex = 188    expect(req.param('id')).toBe('456')89    expect(req.param('name')).toBe('key')90  })9192  test('req.param() returns empty string for missing param', () => {93    const rawRequest = new Request('http://localhost')94    const req = new HonoRequest<'/:remaining'>(rawRequest, '/', [95      [[[undefined, {} as RouterRoute], { remaining: 0 }]],96      [''],97    ])98    expect(req.param('remaining')).toBe('')99  })100101  test('req.param() without argument returns object with empty string for missing param', () => {102    const rawRequest = new Request('http://localhost')103    const req = new HonoRequest<'/:remaining'>(rawRequest, '/', [104      [[[undefined, {} as RouterRoute], { remaining: 0 }]],105      [''],106    ])107    expect(req.param()).toEqual({ remaining: '' })108  })109110  describe('Type', () => {111    it('param() returns string | undefined when P is any (middleware context)', () => {112      // When middleware uses Context without an explicit path type, P defaults to any.113      // param(key) should return string | undefined, not string.114      const rawRequest = new Request('http://localhost/users/123')115      const req = new HonoRequest<any>(rawRequest, '/users/123', [116        [[[undefined, {} as RouterRoute], { id: '123' }]],117      ])118      expectTypeOf(req.param('id')).toEqualTypeOf<string | undefined>()119    })120121    it('param() returns string when P is a known route string', () => {122      // When P is a concrete route, named params should still return string (non-optional).123      const rawRequest = new Request('http://localhost/123')124      const req = new HonoRequest<'/:id'>(rawRequest, '/123', [125        [[[undefined, {} as RouterRoute], { id: '123' }]],126      ])127      expectTypeOf(req.param('id')).toEqualTypeOf<string>()128    })129  })130})131132describe('matchedRoutes', () => {133  test('req.routePath', () => {134    const handlerA = () => {}135    const handlerB = () => {}136    const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')137    const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [138      [139        [140          [handlerA, { basePath: '/', handler: handlerA, method: 'GET', path: '/:id' }],141          { id: '123' },142        ],143        [144          [handlerA, { basePath: '/', handler: handlerB, method: 'GET', path: '/:id/:name' }],145          { id: '456', name: 'key' },146        ],147      ],148    ])149150    expect(req.matchedRoutes).toEqual([151      { basePath: '/', handler: handlerA, method: 'GET', path: '/:id' },152      { basePath: '/', handler: handlerB, method: 'GET', path: '/:id/:name' },153    ])154  })155})156157describe('routePath', () => {158  test('req.routePath', () => {159    const handlerA = () => {}160    const handlerB = () => {}161    const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')162    const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [163      [164        [165          [handlerA, { basePath: '/', handler: handlerA, method: 'GET', path: '/:id' }],166          { id: '123' },167        ],168        [169          [handlerA, { basePath: '/', handler: handlerB, method: 'GET', path: '/:id/:name' }],170          { id: '456', name: 'key' },171        ],172      ],173    ])174175    expect(req.routePath).toBe('/:id')176177    req.routeIndex = 1178    expect(req.routePath).toBe('/:id/:name')179  })180})181182describe('req.addValidatedData() and req.data()', () => {183  const rawRequest = new Request('http://localhost')184185  const payload = {186    title: 'hello',187    author: {188      name: 'young man',189      age: 20,190    },191  }192193  test('add data - json', () => {194    const req = new HonoRequest<'/', { json: typeof payload }>(rawRequest)195    req.addValidatedData('json', payload)196    const data = req.valid('json')197    expect(data).toEqual(payload)198  })199200  test('replace data - json', () => {201    const req = new HonoRequest<'/', { json: typeof payload }>(rawRequest)202    req.addValidatedData('json', payload)203    req.addValidatedData('json', {204      tag: ['sport', 'music'],205      author: {206        tall: 170,207      },208    })209    const data = req.valid('json')210    expect(data).toEqual({211      author: {212        tall: 170,213      },214      tag: ['sport', 'music'],215    })216  })217})218219describe('headers', () => {220  test('empty string is a valid header value', () => {221    const req = new HonoRequest(new Request('http://localhost', { headers: { foo: '' } }))222    const foo = req.header('foo')223    expect(foo).toEqual('')224  })225226  test('Keys of the arguments for req.header() are not case-sensitive', () => {227    const req = new HonoRequest(228      new Request('http://localhost', {229        headers: {230          'Content-Type': 'application/json',231          apikey: 'abc',232          lowercase: 'lowercase value',233        },234      })235    )236    expect(req.header('Content-Type')).toBe('application/json')237    expect(req.header('ApiKey')).toBe('abc')238  })239})240241const text = '{"foo":"bar"}'242const json = { foo: 'bar' }243const buffer = new TextEncoder().encode('{"foo":"bar"}').buffer244245describe('Body methods with caching', () => {246  test('req.text()', async () => {247    const req = new HonoRequest(248      new Request('http://localhost', {249        method: 'POST',250        body: text,251      })252    )253    expect(await req.text()).toEqual(text)254    expect(await req.json()).toEqual(json)255    expect(await req.arrayBuffer()).toEqual(buffer)256    expect(await req.blob()).toEqual(257      new Blob([text], {258        type: 'text/plain;charset=utf-8',259      })260    )261  })262263  test('req.json()', async () => {264    const req = new HonoRequest(265      new Request('http://localhost', {266        method: 'POST',267        body: '{"foo":"bar"}',268      })269    )270    expect(await req.json()).toEqual(json)271    expect(await req.text()).toEqual(text)272    expect(await req.arrayBuffer()).toEqual(buffer)273    expect(await req.blob()).toEqual(274      new Blob([text], {275        type: 'text/plain;charset=utf-8',276      })277    )278  })279280  test('req.json() should keep the content as is', async () => {281    const text = '{ "foo" : "bar" }'282    const req = new HonoRequest(283      new Request('http://localhost', {284        method: 'POST',285        body: text,286      })287    )288    expect(await req.json()).toEqual(JSON.parse(text))289    expect(await req.text()).toEqual(text)290  })291292  test('req.arrayBuffer()', async () => {293    const buffer = new TextEncoder().encode('{"foo":"bar"}').buffer294    const req = new HonoRequest(295      new Request('http://localhost', {296        method: 'POST',297        body: buffer,298      })299    )300    expect(await req.arrayBuffer()).toEqual(buffer)301    expect(await req.text()).toEqual(text)302    expect(await req.json()).toEqual(json)303    expect(await req.blob()).toEqual(304      new Blob([text], {305        type: '',306      })307    )308  })309310  test('req.blob()', async () => {311    const blob = new Blob(['{"foo":"bar"}'], {312      type: 'application/json',313    })314    const req = new HonoRequest(315      new Request('http://localhost', {316        method: 'POST',317        body: blob,318      })319    )320    expect(await req.blob()).toEqual(blob)321    expect(await req.text()).toEqual(text)322    expect(await req.json()).toEqual(json)323    expect(await req.arrayBuffer()).toEqual(buffer)324  })325326  test('req.formData()', async () => {327    const data = new FormData()328    data.append('foo', 'bar')329    const req = new HonoRequest(330      new Request('http://localhost', {331        method: 'POST',332        body: data,333      })334    )335    expect((await req.formData()).get('foo')).toBe('bar')336    expect(async () => await req.text()).not.toThrow()337    expect(async () => await req.arrayBuffer()).not.toThrow()338    expect(async () => await req.blob()).not.toThrow()339  })340341  describe('req.parseBody()', async () => {342    it('should parse form data', async () => {343      const data = new FormData()344      data.append('foo', 'bar')345      const req = new HonoRequest(346        new Request('http://localhost', {347          method: 'POST',348          body: data,349        })350      )351      expect((await req.parseBody())['foo']).toBe('bar')352      expect(async () => await req.text()).not.toThrow()353      expect(async () => await req.arrayBuffer()).not.toThrow()354      expect(async () => await req.blob()).not.toThrow()355    })356357    describe('should not break body methods after parseBody() with non-form content-type', () => {358      const createReq = () =>359        new HonoRequest(360          new Request('http://localhost', {361            method: 'POST',362            body: JSON.stringify({ event: 'push' }),363            headers: { 'Content-Type': 'application/json' },364          })365        )366367      it('text()', async () => {368        const req = createReq()369        await req.parseBody()370        expect(await req.text()).toBe(JSON.stringify({ event: 'push' }))371      })372373      it('json()', async () => {374        const req = createReq()375        await req.parseBody()376        expect(await req.json()).toEqual({ event: 'push' })377      })378379      it('arrayBuffer()', async () => {380        const req = createReq()381        await req.parseBody()382        expect(await req.arrayBuffer()).toBeInstanceOf(ArrayBuffer)383      })384385      it('blob()', async () => {386        const req = createReq()387        await req.parseBody()388        expect(await req.blob()).toBeInstanceOf(Blob)389      })390391      it('formData()', async () => {392        const req = createReq()393        await req.parseBody()394        // application/json is not a valid formData content-type, so this should throw395        expect(req.formData()).rejects.toThrow()396      })397    })398399    describe('Return type', () => {400      let req: HonoRequest401      beforeEach(() => {402        const data = new FormData()403        data.append('foo', 'bar')404        req = new HonoRequest(405          new Request('http://localhost', {406            method: 'POST',407            body: data,408          })409        )410      })411412      it('without options', async () => {413        expectTypeOf((await req.parseBody())['key']).toEqualTypeOf<string | File>()414      })415416      it('{all: true}', async () => {417        expectTypeOf((await req.parseBody({ all: true }))['key']).toEqualTypeOf<418          string | File | (string | File)[]419        >()420      })421422      it('{dot: true}', async () => {423        expectTypeOf((await req.parseBody({ dot: true }))['key']).toEqualTypeOf<424          string | File | RecursiveRecord<string, string | File>425        >()426      })427428      it('{all: true, dot: true}', async () => {429        expectTypeOf((await req.parseBody({ all: true, dot: true }))['key']).toEqualTypeOf<430          | string431          | File432          | (string | File)[]433          | RecursiveRecord<string, string | File | (string | File)[]>434        >()435      })436437      it('specify return type explicitly', async () => {438        expectTypeOf(439          await req.parseBody<{ key1: string; key2: string }>({ all: true, dot: true })440        ).toEqualTypeOf<{ key1: string; key2: string }>()441      })442    })443  })444})445446describe('cloneRawRequest', () => {447  test('clones unconsumed request object', async () => {448    const req = new HonoRequest(449      new Request('http://localhost', {450        method: 'POST',451        headers: {452          'Content-Type': 'application/json',453          'X-Custom-Header': 'custom-value',454        },455        body: text,456        cache: 'no-cache',457        credentials: 'include',458        integrity: 'sha256-test',459        mode: 'cors',460        redirect: 'follow',461        referrer: 'http://example.com',462        referrerPolicy: 'origin',463      })464    )465466    const clonedReq = await cloneRawRequest(req)467468    expect(clonedReq.method).toBe('POST')469    expect(clonedReq.url).toBe('http://localhost/')470    expect(await clonedReq.text()).toBe(text)471    expect(clonedReq.headers.get('Content-Type')).toBe('application/json')472    expect(clonedReq.headers.get('X-Custom-Header')).toBe('custom-value')473    expect(clonedReq.cache).toBe('no-cache')474    expect(clonedReq.credentials).toBe('include')475    expect(clonedReq.integrity).toBe('sha256-test')476    expect(clonedReq.mode).toBe('cors')477    expect(clonedReq.redirect).toBe('follow')478    expect(clonedReq.referrer).toBe('http://example.com/')479    expect(clonedReq.referrerPolicy).toBe('origin')480    expect(req.raw, 'cloned request should be a different object reference').not.toBe(clonedReq)481    expect(req.raw, 'cloned request should contain the same properties').toMatchObject(clonedReq)482  })483484  test('clones consumed request object', async () => {485    const req = new HonoRequest(486      new Request('http://localhost', {487        method: 'POST',488        headers: {489          Authorization: 'Bearer token123',490        },491        body: text,492        mode: 'same-origin',493        credentials: 'same-origin',494      })495    )496    await req.json()497498    const clonedReq = await cloneRawRequest(req)499500    expect(clonedReq.method).toBe('POST')501    expect(clonedReq.url).toBe('http://localhost/')502    expect(await clonedReq.json()).toEqual(json)503    expect(clonedReq.headers.get('Authorization')).toBe('Bearer token123')504    expect(clonedReq.mode).toBe('same-origin')505    expect(clonedReq.credentials).toBe('same-origin')506    expect(req.raw, 'cloned request should be a different object reference').not.toBe(clonedReq)507    expect(req.raw, 'cloned request should contain the same properties').toMatchObject(clonedReq)508  })509510  test('clones GET request without body', async () => {511    const req = new HonoRequest(512      new Request('http://localhost', {513        method: 'GET',514        headers: {515          'User-Agent': 'test-agent',516        },517        cache: 'default',518        redirect: 'manual',519        referrerPolicy: 'no-referrer',520      })521    )522523    const clonedReq = await cloneRawRequest(req)524525    expect(clonedReq.method).toBe('GET')526    expect(clonedReq.url).toBe('http://localhost/')527    expect(clonedReq.headers.get('User-Agent')).toBe('test-agent')528    expect(clonedReq.cache).toBe('default')529    expect(clonedReq.redirect).toBe('manual')530    expect(clonedReq.referrerPolicy).toBe('no-referrer')531    expect(req.raw, 'cloned request should be a different object reference').not.toBe(clonedReq)532    expect(req.raw, 'cloned request should contain the same properties').toMatchObject(clonedReq)533  })534535  test('clones request when raw body was consumed directly without HonoRequest methods', async () => {536    const req = new HonoRequest(537      new Request('http://localhost', {538        method: 'POST',539        headers: {540          'Content-Type': 'application/json',541        },542        body: text,543      })544    )545546    // Consume the raw request body directly, bypassing HonoRequest methods547    // This means bodyCache will be empty548    await req.raw.text()549550    expect(req.raw.bodyUsed).toBe(true)551    expect(Object.keys(req.bodyCache).length).toBe(0)552553    let error: HTTPException | undefined = undefined554    try {555      await cloneRawRequest(req)556    } catch (e) {557      expect(e).toBeInstanceOf(HTTPException)558      error = e as HTTPException559    }560561    expect(error).not.toBeUndefined()562    expect((error as HTTPException).status).toBe(500)563    expect((error as HTTPException).message).toContain(564      'Cannot clone request: body was already consumed and not cached'565    )566  })567})