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.
84 lines
2.1 KiB
84 lines
2.1 KiB
10 years ago
|
|
||
|
var logger = require('../src/logger'),
|
||
|
indeces = require('../query/indeces');
|
||
|
|
||
|
// validate inputs, convert types and apply defaults
|
||
|
function sanitize( params, cb ){
|
||
|
|
||
|
var clean = {};
|
||
|
|
||
|
// ensure the input params are a valid object
|
||
|
if( Object.prototype.toString.call( params ) !== '[object Object]' ){
|
||
|
params = {};
|
||
|
}
|
||
|
|
||
|
// input text
|
||
|
if('string' !== typeof params.input || !params.input.length){
|
||
10 years ago
|
return cb( 'invalid param \'input\': text length, must be >0' );
|
||
10 years ago
|
}
|
||
|
clean.input = params.input;
|
||
|
|
||
|
// total results
|
||
|
var size = parseInt( params.size, 10 );
|
||
|
if( !isNaN( size ) ){
|
||
10 years ago
|
clean.size = Math.min( Math.max( size, 1 ), 40 ); // max
|
||
10 years ago
|
} else {
|
||
|
clean.size = 10; // default
|
||
|
}
|
||
|
|
||
|
// which layers to query
|
||
|
if('string' === typeof params.layers && params.layers.length){
|
||
|
var layers = params.layers.split(',').map( function( layer ){
|
||
|
return layer.toLowerCase(); // lowercase inputs
|
||
|
});
|
||
|
for( var x=0; x<layers.length; x++ ){
|
||
|
if( -1 === indeces.indexOf( layers[x] ) ){
|
||
10 years ago
|
return cb( 'invalid param \'layer\': must be one or more of ' + indeces.join(',') );
|
||
10 years ago
|
}
|
||
|
}
|
||
|
clean.layers = layers;
|
||
|
}
|
||
|
else {
|
||
|
clean.layers = indeces; // default (all layers)
|
||
|
}
|
||
|
|
||
|
// lat
|
||
|
var lat = parseFloat( params.lat, 10 );
|
||
|
if( isNaN( lat ) || lat < 0 || lat > 90 ){
|
||
10 years ago
|
return cb( 'invalid param \'lat\': must be >0 and <90' );
|
||
10 years ago
|
}
|
||
|
clean.lat = lat;
|
||
|
|
||
|
// lon
|
||
|
var lon = parseFloat( params.lon, 10 );
|
||
|
if( isNaN( lon ) || lon < -180 || lon > 180 ){
|
||
10 years ago
|
return cb( 'invalid param \'lon\': must be >-180 and <180' );
|
||
10 years ago
|
}
|
||
|
clean.lon = lon;
|
||
|
|
||
|
// zoom level
|
||
|
var zoom = parseInt( params.zoom, 10 );
|
||
|
if( !isNaN( zoom ) ){
|
||
10 years ago
|
clean.zoom = Math.min( Math.max( zoom, 1 ), 18 ); // max
|
||
10 years ago
|
} else {
|
||
|
clean.zoom = 10; // default
|
||
|
}
|
||
|
|
||
|
return cb( undefined, clean );
|
||
|
|
||
|
}
|
||
|
|
||
10 years ago
|
// export function
|
||
|
module.exports = sanitize;
|
||
|
|
||
10 years ago
|
// middleware
|
||
10 years ago
|
module.exports.middleware = function( req, res, next ){
|
||
10 years ago
|
sanitize( req.query, function( err, clean ){
|
||
10 years ago
|
if( err ){
|
||
|
res.status(400); // 400 Bad Request
|
||
|
return next(err);
|
||
|
}
|
||
10 years ago
|
req.clean = clean;
|
||
|
next();
|
||
|
});
|
||
|
};
|