UNPKG

1.06 kBJavaScriptView Raw
1
2var debug = require('./_debug');
3// debug.enabled = true;
4
5function searchExtractor( cb ){
6
7 // es callback
8 var extractor = function( error, resp ){
9
10 // Response logger
11 debug.resp( resp );
12
13 // Handle errors from the es client
14 if( error ) return cb( error );
15
16 // Handle errors returned in the body
17 if( 'object' == typeof resp && resp.hasOwnProperty('error') ) return cb( resp.error );
18
19 // Check the response is valid ang contains at least one records
20 else if( 'object' == typeof resp && resp.hasOwnProperty('hits') &&
21 Array.isArray( resp.hits.hits ) && resp.hits.hits.length ){
22
23 var results = resp.hits.hits.map( function( doc ){
24 var source = doc._source;
25 source._index = doc._index;
26 source._type = doc._type;
27 source._id = doc._id;
28 return source;
29 });
30
31 return cb( undefined, results );
32 }
33
34 // The query returned 0 results
35 else return cb();
36 return cb( 'an unexpected error occured' );
37 }
38
39 return extractor;
40}
41
42module.exports = searchExtractor;
\No newline at end of file