From 2ee32f18921ca18ce96b83ddff9133db1cb219d7 Mon Sep 17 00:00:00 2001 From: Peter Johnson Date: Mon, 3 Nov 2014 14:12:35 +0000 Subject: [PATCH] mget service --- controller/doc.js | 26 ++++++-------------------- service/mget.js | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 20 deletions(-) create mode 100644 service/mget.js 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