UNPKG

1.91 kBJavaScriptView Raw
1
2var debug = require('./_debug');
3// debug.enabled = true;
4
5function fieldsExtractor( fields, cb ){
6
7 if( !Array.isArray( fields ) || !fields.length ){
8 throw new Error( 'invalid fields supplied' );
9 }
10
11 // es callback
12 var extractor = function( error, resp ){
13
14 // Response logger
15 debug.resp( resp );
16
17 // Handle errors from the es client
18 if( error ) return cb( error );
19
20 // Handle errors returned in the body
21 if( 'object' == typeof resp && resp.hasOwnProperty('error') ) return cb( resp.error );
22
23 // Check the response is valid ang contains at least one records
24 else if( 'object' == typeof resp && resp.hasOwnProperty('hits') &&
25 Array.isArray( resp.hits.hits ) && resp.hits.hits.length ){
26
27 var results = [];
28
29 // iterate through results
30 for( var x=0; x<resp.hits.hits.length; x++ ){
31
32 var hit = resp.hits.hits[x];
33
34 // We only need the document fields
35 var hitFields = hit.fields;
36
37 // This should never happen but was reported in the wild
38 // please report this bug if you see it again
39 if( !hitFields ){
40 console.error( 'fieldsExtractor: invalid fields returned' );
41 console.error( JSON.stringify( resp, null, 2 ) );
42 return cb( 'invalid fields returned' );
43 }
44
45 // Return field data
46 else {
47 var output = {
48 _index: hit._index,
49 _type: hit._type,
50 _id: hit._id
51 }
52 for( var field in hitFields ){
53 output[field] = hitFields[field][0];
54 }
55 if( Object.keys( output ).length > 3 ){
56 results.push( output );
57 }
58 }
59 }
60
61 return cb( undefined, results );
62 }
63
64 // The query returned 0 results
65 else return cb();
66 return cb( 'an unexpected error occured' );
67 }
68
69 return extractor;
70}
71
72module.exports = fieldsExtractor;
\No newline at end of file