UNPKG

1.68 kBJavaScriptView Raw
1const _ = require('lodash')
2
3/**
4 * @function
5 * @private
6 *
7 * @description
8 * Validate the total parameter in the query or the options
9 *
10 * @param {number} total The per_page parameter to be validated
11 * @returns {boolean} The parameter is valid
12 */
13function validateTotal (total) {
14 return _.toInteger(total) >= 0 && !_.isString(total)
15}
16
17/**
18 * @function
19 * @private
20 *
21 * @description
22 * Validate the per_page parameter in the query or the options
23 *
24 * @param {number} perPage The per_page parameter to be validated
25 * @returns {boolean} The parameter is valid
26 */
27function validatePerPage (perPage) {
28 return _.inRange(_.toInteger(perPage), 1, 500 + 1)
29}
30
31/**
32 * @function
33 * @public
34 *
35 * @description
36 * Validate the passed in options
37 *
38 * @param {Object} options The options to be validated
39 * @returns {boolean} The options are valid
40 */
41function validateOptions (options) {
42 return _.isString(options.key) &&
43 validatePerPage(options.perPage) &&
44 validateTotal(options.total)
45}
46
47/**
48 * @function
49 * @public
50 *
51 * @description
52 * Validate the passed query parameters
53 *
54 * @param {Object} query The query object to be validated
55 * @param {Object} options The related options
56 * @param {Object} paramNames The names of the query params
57 * @returns {Object} The query parameters are valid
58 */
59function validateQuery (query, options, paramNames) {
60 query[paramNames.perPage] = _.toInteger(query[paramNames.perPage] || options.perPage)
61 query[paramNames.page] = _.toInteger(query[paramNames.page] || 1)
62
63 return query[paramNames.page] >= 1 && validatePerPage(query[paramNames.perPage])
64}
65
66module.exports = {
67 options: validateOptions,
68 query: validateQuery
69}