diff --git a/controller/search.js b/controller/search.js index 0ed1f9cd..2e8ca7e2 100644 --- a/controller/search.js +++ b/controller/search.js @@ -1,5 +1,4 @@ var service = { search: require('../service/search') }; -var types = require ( '../helper/types' ); function setup( backend, query ){ @@ -16,11 +15,9 @@ function setup( backend, query ){ body: query( req.clean ) }; - // don't directly set cmd.type from types helper to avoid sometimes - // setting cmd.type to undefined (having the key not set is cleaner) - var type = types(req.clean.types); - if (type !== undefined) { - cmd.type = type; + if (req.clean.type !== undefined) { + cmd.type = req.clean.type; + delete req.clean.type; // remove type from clean to avoid clutter } // query backend diff --git a/middleware/_types.js b/middleware/_types.js new file mode 100644 index 00000000..8b12719f --- /dev/null +++ b/middleware/_types.js @@ -0,0 +1,27 @@ +var types_helper = require( '../helper/types' ); + +/** + * Validate the types specified to be searched. + * + * Elasticsearch interprets an empty array of types as "search anything" rather + * than "search nothing", so in the case of an empty array, return an error + * message instead of searching at all. + */ +function middleware(req, res, next) { + var types = types_helper(req.clean.types); + + if (types !== undefined && types.length !== undefined) { + if (types.length === 0) { + var err = 'You have specified both the `source` and `layers` ' + + 'parameters in a combination that will return no results.'; + res.status(400); // 400 Bad Request + return next(err); + } else { + req.clean.type = types; + } + } + + next(); +} + +module.exports = middleware; diff --git a/routes/v1.js b/routes/v1.js index 27bda868..24ecccf2 100644 --- a/routes/v1.js +++ b/routes/v1.js @@ -9,6 +9,11 @@ var sanitisers = { reverse: require('../sanitiser/reverse') }; +/** ----------------------- middleware ------------------------ **/ +var middleware = { + types: require('../middleware/_types') +}; + /** ----------------------- controllers ----------------------- **/ var controllers = { @@ -45,6 +50,7 @@ function addRoutes(app, peliasConfig) { ]), search: createRouter([ sanitisers.search.middleware, + middleware.types, controllers.search(), postProc.confidenceScores(peliasConfig), postProc.renamePlacenames(), diff --git a/sanitiser/search.js b/sanitiser/search.js index d226dbd9..17409587 100644 --- a/sanitiser/search.js +++ b/sanitiser/search.js @@ -4,6 +4,7 @@ var _sanitize = require('../sanitiser/_sanitize'), input: require('../sanitiser/_input'), size: require('../sanitiser/_size'), layers: require('../sanitiser/_layers'), + source: require('../sanitiser/_source'), details: require('../sanitiser/_details'), latlonzoom: require('../sanitiser/_geo') };