Merge pull request #1722 from Omar-Tnt04/fix-invalid-body-status

This commit is contained in:
typicode
2026-03-11 20:25:29 +01:00
committed by GitHub
2 changed files with 41 additions and 4 deletions

View File

@@ -142,4 +142,37 @@ await test('createApp', async (t) => {
const data = await response.json()
assert.deepEqual(data, [{ id: '1', title: 'foo' }])
})
await t.test('POST /posts with array body returns 400', async () => {
const response = await fetch(`http://localhost:${port}/posts`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify([{ title: 'foo' }]),
})
assert.equal(response.status, 400)
const data = await response.json()
assert.deepEqual(data, { error: 'Body must be a JSON object' })
})
await t.test('PATCH /posts/1 with string body returns 400', async () => {
const response = await fetch(`http://localhost:${port}/posts/1`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify('hello'),
})
assert.equal(response.status, 400)
const data = await response.json()
assert.deepEqual(data, { error: 'Body must be a JSON object' })
})
await t.test('PUT /posts/1 with null body returns 400', async () => {
const response = await fetch(`http://localhost:${port}/posts/1`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(null),
})
assert.equal(response.status, 400)
const data = await response.json()
assert.deepEqual(data, { error: 'Body must be a JSON object' })
})
})

View File

@@ -68,9 +68,11 @@ function parseListParams(req: any) {
function withBody(action: (name: string, body: Record<string, unknown>) => Promise<unknown>) {
return async (req: any, res: any, next: any) => {
const { name = '' } = req.params
if (isItem(req.body)) {
res.locals['data'] = await action(name, req.body)
if (!isItem(req.body)) {
res.status(400).json({ error: 'Body must be a JSON object' })
return
}
res.locals['data'] = await action(name, req.body)
next?.()
}
}
@@ -80,9 +82,11 @@ function withIdAndBody(
) {
return async (req: any, res: any, next: any) => {
const { name = '', id = '' } = req.params
if (isItem(req.body)) {
res.locals['data'] = await action(name, id, req.body)
if (!isItem(req.body)) {
res.status(400).json({ error: 'Body must be a JSON object' })
return
}
res.locals['data'] = await action(name, id, req.body)
next?.()
}
}