Skip to content

Commit

Permalink
fix: should override value if option is false
Browse files Browse the repository at this point in the history
  • Loading branch information
fzn0x committed May 15, 2024
1 parent cd1055f commit 716de84
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
14 changes: 14 additions & 0 deletions src/utils/body.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,20 @@ describe('Parse Body Util', () => {
})
})

it('should override value if `all` option is false', async () => {
const data = new FormData()
data.append('file', 'aaa')
data.append('file', 'bbb')
data.append('message', 'hello')

const req = createRequest(FORM_URL, 'POST', data)

expect(await parseBody(req)).toEqual({
file: 'bbb',
message: 'hello',
})
})

it('should parse multiple values if `all` option is true', async () => {
const data = new FormData()
data.append('file', 'aaa')
Expand Down
18 changes: 11 additions & 7 deletions src/utils/body.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export type ParseBodyOptions = {

export const parseBody = async <T extends BodyData = BodyData>(
request: HonoRequest | Request,
options: ParseBodyOptions = {}
options: ParseBodyOptions = Object.create(null)
): Promise<T> => {
const { all = false, dot = false } = options

Expand Down Expand Up @@ -72,7 +72,7 @@ function convertFormDataToBodyData<T extends BodyData = BodyData>(
formData: FormData,
options: ParseBodyOptions
): T {
const form: BodyData = {}
const form: BodyData = Object.create(null)

formData.forEach((value, key) => {
const shouldParseAllValues = options.all || key.endsWith('[]')
Expand Down Expand Up @@ -140,17 +140,21 @@ const handleNestedValues = (
typeof nestedForm[key] !== 'object' ||
Array.isArray(nestedForm[key])
) {
nestedForm[key] = {}
nestedForm[key] = Object.create(null)
}
nestedForm = nestedForm[key] as BodyData
}
})
} else {
if (form[key] !== undefined) {
if (Array.isArray(form[key])) {
;(form[key] as (string | File)[]).push(value)
if (parseAllValues) {
if (form[key] !== undefined) {
if (Array.isArray(form[key])) {
;(form[key] as (string | File)[]).push(value)
} else {
form[key] = [form[key] as string | File, value]
}
} else {
form[key] = [form[key] as string | File, value]
form[key] = value
}
} else {
form[key] = value
Expand Down

0 comments on commit 716de84

Please sign in to comment.