/
integration.js
269 lines (229 loc) · 6.56 KB
/
integration.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
'use strict';
const request = require('postman-request');
const config = require('./config/config');
const icons = require('./src/icons');
const async = require('async');
const { v4: uuidv4 } = require('uuid');
const fs = require('fs');
let Logger;
let requestWithDefaults;
const MAX_PARALLEL_LOOKUPS = 10;
const SEARCH_ENGINE_ID = '0429b9e2e8aac5810';
function startup(logger) {
let defaults = {};
Logger = logger;
const { cert, key, passphrase, ca, proxy, rejectUnauthorized } = config.request;
if (typeof cert === 'string' && cert.length > 0) {
defaults.cert = fs.readFileSync(cert);
}
if (typeof key === 'string' && key.length > 0) {
defaults.key = fs.readFileSync(key);
}
if (typeof passphrase === 'string' && passphrase.length > 0) {
defaults.passphrase = passphrase;
}
if (typeof ca === 'string' && ca.length > 0) {
defaults.ca = fs.readFileSync(ca);
}
if (typeof proxy === 'string' && proxy.length > 0) {
defaults.proxy = proxy;
}
if (typeof rejectUnauthorized === 'boolean') {
defaults.rejectUnauthorized = rejectUnauthorized;
}
requestWithDefaults = request.defaults(defaults);
}
function _createQuery(entity, searchFilters) {
let query = `"${entity.value.replace('=',' ')}"`;
searchFilters.forEach((filter) => {
if (filter.value === true) {
query += ` site:${filter.filterValue} OR `;
}
});
return query;
}
function _searchEntity(entity, searchFilters, options, cb) {
const requestOptions = {
method: 'GET',
uri: 'https://www.googleapis.com/customsearch/v1/',
qs: {
key: options.apiKey,
cx: SEARCH_ENGINE_ID,
num: 10, // 10 is the max allowed by the API
q: _createQuery(entity, searchFilters),
quotaUser: uuidv4()
},
json: true
};
Logger.trace({ requestOptions }, 'Request Options');
requestWithDefaults(requestOptions, function (error, res, body) {
let processedResult = handleRestError(error, entity, res, body);
Logger.trace({ body, status: res ? res.statusCode : 'Not Available' }, 'Result');
if (processedResult.error) {
cb(processedResult);
return;
}
cb(null, processedResult);
});
}
function _formatDetails(body) {
// The return result contains a lot additional information we don't use, pluck out just the fields
// we display in the template to reduce the amount of cached data and the size of the return payload
const items = body.items.map((item) => {
const icon = icons.displayNameToIcon[item.displayLink];
return {
icon: icon ? icon : '',
displayLink: item.displayLink,
title: item.title,
link: item.link,
snippet: item.snippet
};
});
return {
icons: icons.icons,
searchResults: {
searchInformation: body.searchInformation,
items
}
};
}
function doLookup(entities, options, cb) {
let lookupResults = [];
let tasks = [];
const NO_SEARCH_FILTER = [];
Logger.debug({ entities, options }, 'doLookup');
entities.forEach((entity) => {
tasks.push(function (done) {
_searchEntity(entity, NO_SEARCH_FILTER, options, done);
});
});
async.parallelLimit(tasks, MAX_PARALLEL_LOOKUPS, (err, results) => {
if (err) {
Logger.error({ err: err }, 'Error');
cb(err);
return;
}
results.forEach((result) => {
if (_isMiss(result.body)) {
lookupResults.push({
entity: result.entity,
data: null
});
} else {
lookupResults.push({
entity: result.entity,
displayValue: `${result.entity.value.slice(0, 120)}${
result.entity.value.length > 120 ? '...' : ''
}`,
data: {
summary: [`${result.body.searchInformation.totalResults} results`],
details: _formatDetails(result.body)
}
});
}
});
Logger.debug({ lookupResults }, 'Results');
cb(null, lookupResults);
});
}
function _isMiss(body) {
return body === null || body.searchInformation.totalResults === '0';
}
function handleRestError(error, entity, res, body) {
let result;
if (error || !body) {
return {
error,
body,
detail: 'HTTP Request Error'
};
}
if (res.statusCode === 400) {
return {
error: body.error && body.error.message ? body.error.message : 'There was an error in the request',
statusCode: res ? res.statusCode : 'Unknown',
detail: body.error && body.error.message ? body.error.message : 'There was an error in the request'
};
}
if (res.statusCode === 429) {
return {
error: body.error && body.error.message ? body.error.message : 'Search quota exceeded',
statusCode: res ? res.statusCode : 'Unknown',
detail: 'Search quota exceeded'
};
}
if (res.statusCode === 403) {
return {
error: body.error && body.error.message ? body.error.message : 'The request is missing a valid API key.',
statusCode: res ? res.statusCode : 'Unknown',
detail: 'The request is missing a valid API key.'
};
}
if (res.statusCode !== 200) {
return {
error: 'Did not receive HTTP 200 Status Code',
statusCode: res ? res.statusCode : 'Unknown',
detail: 'An unexpected error occurred',
body,
res
};
}
if (res.statusCode === 200) {
// we got data!
result = {
entity: entity,
body: body
};
} else {
result = {
body,
errorNumber: body.errorNo,
error: body.errorMsg,
detail: body.errorMsg
};
}
return result;
}
function onMessage(payload, options, cb) {
Logger.trace({ payload }, 'onMessage');
_searchEntity(payload.entity, payload.searchFilters, options, (err, result) => {
if (err) {
Logger.error({ err }, 'Error in onMessage');
cb(err);
} else {
if (_isMiss(result.body)) {
Logger.trace('onMessage results are a miss');
// This return payload mimics no results
cb(null, {
searchInformation: {
totalResults: 0
},
items: []
});
} else {
const details = _formatDetails(result.body);
Logger.trace({ details }, 'onMessage');
cb(null, details.searchResults);
}
}
});
}
function validateOptions(userOptions, cb) {
let errors = [];
if (
typeof userOptions.apiKey.value !== 'string' ||
(typeof userOptions.apiKey.value === 'string' && userOptions.apiKey.value.length === 0)
) {
errors.push({
key: 'apiKey',
message: 'You must provide a valid Google API key'
});
}
cb(null, errors);
}
module.exports = {
doLookup,
startup,
onMessage,
validateOptions
};