-
Notifications
You must be signed in to change notification settings - Fork 2
/
parse-query-string.js
35 lines (32 loc) · 1.13 KB
/
parse-query-string.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function parseQueryString(req, res, next) {
try {
req.query.filter = parseQueryStringObject(req.query.filter, {})
req.query.projection = parseQueryStringObject(req.query.projection, {})
req.query.sort = parseSortOptions(req.query.sort)
req.query.pagination = parseQueryStringObject(req.query.pagination, {
page: 1,
pageSize: 50
})
req.query.keywords = req.query.keywords || ''
next()
} catch (e) {
return res.status(400).json(new Error('Invalid JSON'))
}
}
function parseQueryStringObject(parameter, defaultValue) {
if (!parameter) return defaultValue
var result = JSON.parse(parameter)
if (typeof result !== 'object')
throw new Error('Invalid parameter provided ' + result)
return Object.assign({}, defaultValue, result)
}
function parseSortOptions(parameter) {
if (!parameter) return undefined
const rawOptions = JSON.parse(parameter)
let sort = 'asc'
if (!Array.isArray(rawOptions)) return undefined
if (!rawOptions.length) return undefined
if (typeof rawOptions[1] !== 'undefined') sort = rawOptions[1]
return [[rawOptions[0], sort]]
}
module.exports = parseQueryString