Skip to content

Commit 075ff35

Browse files
authored
Validate empty query body and improve errors (#33)
Reject empty JSON query bodies ('{}' or '[]') with a 400 error to prevent accidental all-data queries. Also set a 400 status for invalid `limit`/`skip` inputs and propagate the error status and message in the response (res.status(err.status ?? 500).send("Caught " + err.message)). Adds clearer error creation and handling for client input validation.
1 parent 8cbc082 commit 075ff35

1 file changed

Lines changed: 11 additions & 2 deletions

File tree

routes/query.js

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,20 @@ router.post('/', async (req, res, next) => {
88
try {
99
// check body for JSON
1010
const queryBody = JSON.stringify(req.body)
11+
// If there is an empty query with [] or {}, we consider that a query for all data,
12+
// which we don't want to allow. We will throw a 400 error.
13+
if (queryBody === '{}' || queryBody === '[]') {
14+
const err = new Error("Empty query is not allowed. Please provide a valid query in the request body.")
15+
err.status = 400
16+
throw err
17+
}
1118
// check limit and skip for INT
1219
if (isNaN(parseInt(lim) + parseInt(skip))
1320
|| (lim < 0)
1421
|| (skip < 0)) {
15-
throw Error("`limit` and `skip` values must be positive integers or omitted.")
22+
const err = new Error("`limit` and `skip` values must be positive integers or omitted.")
23+
err.status = 400
24+
throw err
1625
}
1726
const queryOptions = {
1827
method: 'POST',
@@ -31,7 +40,7 @@ router.post('/', async (req, res, next) => {
3140
}
3241
catch (err) {
3342
console.log(err)
34-
res.status(500).send("Caught " + err)
43+
res.status(err.status ?? 500).send("Caught " + err.message)
3544
}
3645
})
3746

0 commit comments

Comments
 (0)