Skip to content

Commit 80959d4

Browse files
authored
fix(utils/body): reuse cached formData in parseBody() (#5131)
1 parent 21b44b6 commit 80959d4

2 files changed

Lines changed: 22 additions & 0 deletions

File tree

‎src/request.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,22 @@ describe('Body methods with caching', () => {
381381
expect(async () => await req.blob()).not.toThrow()
382382
})
383383

384+
it('should parse form data even if formData() is called before parseBody()', async () => {
385+
const data = new FormData()
386+
data.append('foo', 'bar')
387+
data.append('file', new File(['hello'], 't.txt', { type: 'text/plain' }))
388+
const req = new HonoRequest(
389+
new Request('http://localhost', {
390+
method: 'POST',
391+
body: data,
392+
})
393+
)
394+
await req.formData()
395+
const body = await req.parseBody()
396+
expect(body['foo']).toBe('bar')
397+
expect(body['file']).toBeInstanceOf(File)
398+
})
399+
384400
describe('should not break body methods after parseBody() with non-form content-type', () => {
385401
const createReq = () =>
386402
new HonoRequest(

‎src/utils/body.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,12 @@ async function parseFormData<T extends BodyData>(
124124
request: HonoRequest | Request,
125125
options: ParseBodyOptions
126126
): Promise<T> {
127+
if (!isRawRequest(request) && request.bodyCache.formData) {
128+
return convertFormDataToBodyData<T>(
129+
await (request.bodyCache.formData as FormData | Promise<FormData>),
130+
options
131+
)
132+
}
127133
const headers = isRawRequest(request) ? request.headers : request.raw.headers
128134
const arrayBuffer = await (request as Request).arrayBuffer()
129135
const formDataPromise = bufferToFormData(arrayBuffer, headers.get('Content-Type') || '')

0 commit comments

Comments
 (0)