Skip to content
Snippets Groups Projects
Commit 8c816b73 authored by Vytor Calixto's avatar Vytor Calixto :space_invader:
Browse files

Remove parseParams middleware

parent c3283b10
No related branches found
No related tags found
2 merge requests!116Release v1.0.0,!29Feature param query builder
/**
* ParseParams middleware
*
* EXAMPLE:
* Use it with no parameters to get all the params specified
* app.get('/', parseParams('dims'), function(req, res, next){})
*
* Use it with an array of accepted values
* app.get('/', parseParams('filter', ['year', 'location']), function(req, res, next){})
*
* Use it globally
* app.use(parseParams('dims'))
*/
const libs = `${process.cwd()}/libs`;
const log = require(`${libs}/log`)(module);
const _ = require('lodash')
function parseParams(queryField, arr) {
return (req, res, next) => {
req[queryField] = {};
if (req.query[queryField]) {
const params = req.query[queryField].split(',');
// Temporary object to hold the params and it's values
const obj = {};
for (const param of params) {
// Get the key and the value - state:41 is key 'state' whith value 41.
// kv is then an array [key, value] or [key] if there is no value
const kv = param.split(':');
// Check if there is a value. If there isn't, assign true
obj[kv[0]] = (typeof kv[1] === 'undefined') ? true : kv[1];
}
// If the array exists and is not empty we intersect
if (typeof arr !== 'undefined' && arr.length > 0) {
// Intersect the keys of the obj with the array arr.
// The intersection array is assigned with the keys
const intersection = _.intersection(arr, Object.keys(obj));
// This is a bit tricky...
// For each key in the intersection array we get it's value in the obj
// and assign it to the custom attribute in the req obj.
// For example: instersection => ["state"] so
// obj[intersection[i]] (with i=0) is obj["state"], that is 41
// and req[queryField]["state"] = 41
for (let i = 0; i < intersection.length; ++i) {
req[queryField][intersection[i]] = obj[intersection[i]];
}
req[queryField].size = intersection.length;
} else {
req[queryField] = obj;
req[queryField].size = Object.keys(obj).length;
}
}
next();
};
}
module.exports = parseParams;
......@@ -12,8 +12,6 @@ const query = require(`${libs}/middlewares/query`);
const response = require(`${libs}/middlewares/response`);
const parseParams = require(`${libs}/middlewares/parseParams`);
const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`);
let rqf = new ReqQueryFields();
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment