Skip to content

Commit d2b3dec

Browse files
authored
Merge pull request #1722 from Omar-Tnt04/fix-invalid-body-status
2 parents 3d4262b + 503b969 commit d2b3dec

File tree

2 files changed

+41
-4
lines changed

2 files changed

+41
-4
lines changed

src/app.test.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,4 +142,37 @@ await test('createApp', async (t) => {
142142
const data = await response.json()
143143
assert.deepEqual(data, [{ id: '1', title: 'foo' }])
144144
})
145+
146+
await t.test('POST /posts with array body returns 400', async () => {
147+
const response = await fetch(`http://localhost:${port}/posts`, {
148+
method: 'POST',
149+
headers: { 'Content-Type': 'application/json' },
150+
body: JSON.stringify([{ title: 'foo' }]),
151+
})
152+
assert.equal(response.status, 400)
153+
const data = await response.json()
154+
assert.deepEqual(data, { error: 'Body must be a JSON object' })
155+
})
156+
157+
await t.test('PATCH /posts/1 with string body returns 400', async () => {
158+
const response = await fetch(`http://localhost:${port}/posts/1`, {
159+
method: 'PATCH',
160+
headers: { 'Content-Type': 'application/json' },
161+
body: JSON.stringify('hello'),
162+
})
163+
assert.equal(response.status, 400)
164+
const data = await response.json()
165+
assert.deepEqual(data, { error: 'Body must be a JSON object' })
166+
})
167+
168+
await t.test('PUT /posts/1 with null body returns 400', async () => {
169+
const response = await fetch(`http://localhost:${port}/posts/1`, {
170+
method: 'PUT',
171+
headers: { 'Content-Type': 'application/json' },
172+
body: JSON.stringify(null),
173+
})
174+
assert.equal(response.status, 400)
175+
const data = await response.json()
176+
assert.deepEqual(data, { error: 'Body must be a JSON object' })
177+
})
145178
})

src/app.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,11 @@ function parseListParams(req: any) {
6868
function withBody(action: (name: string, body: Record<string, unknown>) => Promise<unknown>) {
6969
return async (req: any, res: any, next: any) => {
7070
const { name = '' } = req.params
71-
if (isItem(req.body)) {
72-
res.locals['data'] = await action(name, req.body)
71+
if (!isItem(req.body)) {
72+
res.status(400).json({ error: 'Body must be a JSON object' })
73+
return
7374
}
75+
res.locals['data'] = await action(name, req.body)
7476
next?.()
7577
}
7678
}
@@ -80,9 +82,11 @@ function withIdAndBody(
8082
) {
8183
return async (req: any, res: any, next: any) => {
8284
const { name = '', id = '' } = req.params
83-
if (isItem(req.body)) {
84-
res.locals['data'] = await action(name, id, req.body)
85+
if (!isItem(req.body)) {
86+
res.status(400).json({ error: 'Body must be a JSON object' })
87+
return
8588
}
89+
res.locals['data'] = await action(name, id, req.body)
8690
next?.()
8791
}
8892
}

0 commit comments

Comments
 (0)