diff --git a/controller/doc.js b/controller/doc.js index b48e6f64..c945aadb 100644 --- a/controller/doc.js +++ b/controller/doc.js @@ -1,15 +1,15 @@ +var service = { mget: require('../service/mget') }; var geojsonify = require('../helper/geojsonify').search; function setup( backend ){ // allow overriding of dependencies backend = backend || require('../src/backend'); - backend = new backend(); function controller( req, res, next ){ - var docs = req.clean.ids.map( function(id) { + var query = req.clean.ids.map( function(id) { return { _index: 'pelias', _type: id.type, @@ -17,25 +17,10 @@ function setup( backend ){ }; }); - // backend command - var cmd = { - body: { - docs: docs - } - }; - - // query new backend - backend.client.mget( cmd, function( err, data ){ - - var docs = []; - // handle backend errors - if( err ){ return next( err ); } + service.mget( backend, query, function( err, docs ){ - if( data && data.docs && Array.isArray(data.docs) && data.docs.length ){ - docs = data.docs.map( function( doc ){ - return doc._source; - }); - } + // error handler + if( err ){ return next( err ); } // convert docs to geojson var geojson = geojsonify( docs ); @@ -45,6 +30,7 @@ function setup( backend ){ // respond return res.status(200).json( geojson ); + }); } diff --git a/service/mget.js b/service/mget.js new file mode 100644 index 00000000..a5713f03 --- /dev/null +++ b/service/mget.js @@ -0,0 +1,43 @@ + +/** + + query must be an array of hashes, structured like so: + + { + _index: 'myindex', + _type: 'mytype', + _id: 'myid' + } + +**/ + +function service( backend, query, cb ){ + + // backend command + var cmd = { + body: { + docs: query + } + }; + + // query new backend + backend().client.mget( cmd, function( err, data ){ + + // handle backend errors + if( err ){ return cb( err ); } + + // map returned documents + var docs = []; + if( data && Array.isArray(data.docs) ){ + docs = data.docs.map( function( doc ){ + return doc._source; + }); + } + + // fire callback + return cb( null, docs ); + }); + +} + +module.exports = service; \ No newline at end of file