mirror of https://github.com/pelias/api.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
2.1 KiB
75 lines
2.1 KiB
9 years ago
|
var _ = require('lodash'),
|
||
|
check = require('check-types');
|
||
|
|
||
9 years ago
|
function getValidKeys(mapping) {
|
||
|
return _.uniq(Object.keys(mapping)).join(',');
|
||
|
}
|
||
|
|
||
9 years ago
|
function setup( paramName, targetMap ) {
|
||
|
return function( raw, clean ){
|
||
|
return sanitize( raw, clean, {
|
||
|
paramName: paramName,
|
||
|
targetMap: targetMap,
|
||
9 years ago
|
targetMapKeysString: getValidKeys(targetMap)
|
||
9 years ago
|
});
|
||
9 years ago
|
};
|
||
|
}
|
||
|
|
||
9 years ago
|
function sanitize( raw, clean, opts ) {
|
||
|
// error & warning messages
|
||
|
var messages = { errors: [], warnings: [] };
|
||
9 years ago
|
|
||
9 years ago
|
// the string of targets (comma delimeted)
|
||
|
var targetsString = raw[opts.paramName];
|
||
9 years ago
|
|
||
9 years ago
|
// trim whitespace
|
||
9 years ago
|
if( check.nonEmptyString( targetsString ) ){
|
||
9 years ago
|
targetsString = targetsString.trim();
|
||
9 years ago
|
|
||
9 years ago
|
// param must be a valid non-empty string
|
||
9 years ago
|
if( !check.nonEmptyString( targetsString ) ){
|
||
9 years ago
|
messages.errors.push(
|
||
|
opts.paramName + ' parameter cannot be an empty string. Valid options: ' + opts.targetMapKeysString
|
||
|
);
|
||
|
}
|
||
|
else {
|
||
9 years ago
|
|
||
9 years ago
|
// split string in to array and lowercase each target string
|
||
|
var targets = targetsString.split(',').map( function( target ){
|
||
|
return target.toLowerCase(); // lowercase inputs
|
||
|
});
|
||
9 years ago
|
|
||
9 years ago
|
// emit an error for each target *not* present in the targetMap
|
||
|
targets.filter( function( target ){
|
||
|
return !opts.targetMap.hasOwnProperty(target);
|
||
|
}).forEach( function( target ){
|
||
|
messages.errors.push(
|
||
|
'\'' + target + '\' is an invalid ' + opts.paramName + ' parameter. Valid options: ' + opts.targetMapKeysString
|
||
|
);
|
||
|
});
|
||
|
|
||
|
// only set types value when no error occured
|
||
|
if( !messages.errors.length ){
|
||
9 years ago
|
clean[opts.paramName] = targets.reduce(function(acc, target) {
|
||
9 years ago
|
return acc.concat(opts.targetMap[target]);
|
||
|
}, []);
|
||
|
|
||
|
// dedupe in case aliases expanded to common things or user typed in duplicates
|
||
9 years ago
|
clean[opts.paramName] = _.uniq(clean[opts.paramName]);
|
||
9 years ago
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// string is empty
|
||
|
else if( check.string( targetsString ) ){
|
||
|
messages.errors.push(
|
||
|
opts.paramName + ' parameter cannot be an empty string. Valid options: ' + opts.targetMapKeysString
|
||
|
);
|
||
|
}
|
||
9 years ago
|
|
||
|
|
||
9 years ago
|
return messages;
|
||
9 years ago
|
}
|
||
|
|
||
|
module.exports = setup;
|