From 5f8c3da14e849ec3fc3b5d91c104562aa0daa012 Mon Sep 17 00:00:00 2001 From: Harish Krishna Date: Fri, 10 Oct 2014 13:59:43 -0400 Subject: [PATCH] using async (parallel) --- controller/suggest.js | 63 +++++++++++++++++++------------------------ package.json | 3 ++- 2 files changed, 29 insertions(+), 37 deletions(-) diff --git a/controller/suggest.js b/controller/suggest.js index 1fc58812..8e792ff8 100644 --- a/controller/suggest.js +++ b/controller/suggest.js @@ -1,5 +1,6 @@ var geojsonify = require('../helper/geojsonify').suggest; +var async = require('async'); function setup( backend, query ){ @@ -11,59 +12,49 @@ function setup( backend, query ){ backend = backend || require('../src/backend'); var query_admin = require('../query/suggest_admin'); var query_poi = require('../query/suggest_poi'); - - // **query_poi** command var cmd = { - index: 'pelias', - body: query_poi( req.clean ) + index: 'pelias' }; - - // query backend - backend().client.suggest( cmd, function( err, data ){ - - var docs = []; - - // handle backend errors - if( err ){ return next( err ); } - - // map response to a valid FeatureCollection - if( data && Array.isArray( data.pelias ) && data.pelias.length ){ - docs = data['pelias'][0].options || []; - } - - // **query_admin** command - var cmd = { - index: 'pelias', - body: query_admin( req.clean ) - }; - + var query_backend = function(cmd, callback) { // query backend backend().client.suggest( cmd, function( err, data ){ - var docs2 = []; + var docs = []; // handle backend errors if( err ){ return next( err ); } // map response to a valid FeatureCollection if( data && Array.isArray( data.pelias ) && data.pelias.length ){ - docs2 = data['pelias'][0].options || []; + docs = data['pelias'][0].options || []; } - /** --- combine 2 doc sets --- **/ - var combined = docs2.slice(0, 3).concat(docs); - - // convert docs to geojson - var geojson = geojsonify( combined ); + callback(null, docs); + }); + }; - // response envelope - geojson.date = new Date().getTime(); + async.parallel({ + admin: function(callback){ + cmd.body = query_admin( req.clean ); + query_backend(cmd, callback); + }, + poi: function(callback){ + cmd.body = query_poi( req.clean ); + query_backend(cmd, callback); + } + }, + function(err, results) { + // results is now equals to: {admin: docs, poi: docs} + var combined = results.poi.slice(0, 3).concat(results.admin); - // respond - return res.status(200).json( geojson ); + // convert docs to geojson + var geojson = geojsonify( combined ); - }); + // response envelope + geojson.date = new Date().getTime(); + // respond + return res.status(200).json( geojson ); }); } diff --git a/package.json b/package.json index 4d0bfce9..aacccf89 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,8 @@ "geojson": "^0.2.0", "geopipes-elasticsearch-backend": "0.0.8", "pelias-esclient": "0.0.25", - "toobusy": "^0.2.4" + "toobusy": "^0.2.4", + "async": "^0.9.0" }, "devDependencies": { "ciao": "^0.3.4",