app2-api/middlewares/sort.js

67 lines
2.2 KiB
JavaScript
Raw Normal View History

2019-05-09 16:23:54 +00:00
"use strict";
/*
Sort middleware
This module exports a function that takes a configuration object parameter with the following
properties:
{
validKeys: Array of strings (case sensitive),
default: String (optional, by default assigned to the first element of the
validKeys array with ascending sorting order unless prefixed by a "-")
}
and returns an express compatible middleware function (req, res, next) that parses the following
parameters from the req.query object and sets an object on the res.locals.sort having the following
properties:
Object - with keys for the sort value fields and value a boolean denoting ascending order
or not
*/
const middleware = (config) => {
if (typeof config !== "object" || config === null) {
throw new Error("The config parameter is mandatory and should be an object!");
}
config = config || {};
if (!config.default && (!Array.isArray(config.validKeys) || config.validKeys.length === 0)) {
throw new Error("config.validKeys should be a non empty array of strings or a config.default key should be defined!");
}
config.default = config.default || config.validKeys[0];
const defaultSortIsAscending = config.default.substring(0, 1) !== "-";
return function (req, res, next) {
const sortKeys = Array.isArray(req.query.sort)
? req.query.sort
: req.query.sort
? [req.query.sort]
: [];
const sortObject = sortKeys.reduce(function (c, key) {
const ascending = key.substring(0, 1) !== "-";
if (!ascending) {
key = key.substr(1);
}
if (key && config.validKeys && config.validKeys.indexOf(key) !== -1 ) {
c[key] = ascending;
}
return c;
}, {});
if (Object.keys(sortObject).length === 0) {
sortObject[
defaultSortIsAscending
? config.default
: config.default.substr(1)
] = defaultSortIsAscending;
}
res.locals.sort = sortObject;
next();
};
}
module.exports = {
middleware
}