Skip to content

Commit

Permalink
fix: Fixed to return 400 response when the request body is not FormData
Browse files Browse the repository at this point in the history
  • Loading branch information
uttk committed Jul 27, 2024
1 parent 846741a commit 5ed2084
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
6 changes: 5 additions & 1 deletion packages/conform-validator/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import type { Context } from 'hono'
import { bufferToFormData } from 'hono/utils/buffer'

// ref: https://github.com/honojs/hono/blob/a63bcfd6fba66297d8234c21aed8a42ac00711fe/src/validator/validator.ts#L27-L28
const multipartRegex = /^multipart\/form-data(; boundary=[A-Za-z0-9'()+_,\-./:=?]+)?$/
const urlencodedRegex = /^application\/x-www-form-urlencoded$/

export const getFormDataFromContext = async (ctx: Context): Promise<FormData> => {
const contentType = ctx.req.header('Content-Type')
if (!contentType) {
if (!contentType || !(multipartRegex.test(contentType) || urlencodedRegex.test(contentType))) {
return new FormData()
}

Expand Down
35 changes: 35 additions & 0 deletions packages/conform-validator/test/common.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Hono } from 'hono'
import { z } from 'zod'
import { parseWithZod } from '@conform-to/zod'
import { conformValidator } from '../src'

describe('Validate common processing', () => {
const app = new Hono()
const schema = z.object({ name: z.string() })
const route = app.post(
'/author',
conformValidator((formData) => parseWithZod(formData, { schema })),
(c) => {
const submission = c.req.valid('form')
const value = submission.value
return c.json({ success: true, message: `my name is ${value.name}` })
}
)

describe('When the request body is empty', () => {
it('Should return 400 response', async () => {
const res = await route.request('/author', { method: 'POST' })
expect(res.status).toBe(400)
})
})

describe('When the request body is not FormData', () => {
it('Should return 400 response', async () => {
const res = await route.request('/author', {
method: 'POST',
body: JSON.stringify({ name: 'Space Cat!' }),
})
expect(res.status).toBe(400)
})
})
})

0 comments on commit 5ed2084

Please sign in to comment.