-
Notifications
You must be signed in to change notification settings - Fork 0
/
contactV2Change.js
352 lines (307 loc) · 10.2 KB
/
contactV2Change.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
'use strict';
var raven = require('raven');
var elasticsearch = require('elasticsearch');
var rp = require('request-promise');
var Q = require('q');
var gcloud = require('google-cloud')({
projectId: 'newsai-1166'
});
// Instantiate a datastore client
var datastore = require('@google-cloud/datastore')({
projectId: 'newsai-1166'
});
// Instantiate a elasticsearch client
var client = new elasticsearch.Client({
host: 'https://newsai:[email protected]',
// log: 'trace',
rejectUnauthorized: false
});
// Instantiate a sentry client
var sentryClient = new raven.Client('https://f4ab035568994293b9a2a90727ccb5fc:[email protected]/103134');
sentryClient.patchGlobal();
// Initialize Google Cloud
var topicName = 'process-contact-change';
var subscriptionName = 'node-contact-change';
var pubsub = gcloud.pubsub();
// Get a Google Cloud topic
function getTopic(currentTopicName, cb) {
pubsub.createTopic(currentTopicName, function(err, topic) {
// topic already exists.
if (err && err.code === 409) {
return cb(null, pubsub.topic(currentTopicName));
}
return cb(err, topic);
});
}
/**
* Gets a Datastore key from the kind/key pair in the request.
*
* @param {Object} requestData Cloud Function request data.
* @param {string} requestData.Id Datastore ID string.
* @returns {Object} Datastore key object.
*/
function getKeysFromRequestData(requestData, resouceType) {
if (!requestData.Id) {
throw new Error("Id not provided. Make sure you have a 'Id' property " +
"in your request");
}
var ids = requestData.Id.split(',');
var keys = [];
for (var i = ids.length - 1; i >= 0; i--) {
var contactId = parseInt(ids[i], 10);
var datastoreId = datastore.key([resouceType, contactId]);
keys.push(datastoreId);
}
return keys;
}
/**
* Retrieves a record.
*
* @example
* gcloud alpha functions call ds-get --data '{'kind':'gcf-test','key':'foobar'}'
*
* @param {Object} context Cloud Function context.
* @param {Function} context.success Success callback.
* @param {Function} context.failure Failure callback.
* @param {Object} data Request data, in this case an object provided by the user.
* @param {string} data.kind The Datastore kind of the data to retrieve, e.g. 'user'.
* @param {string} data.key Key at which to retrieve the data, e.g. 5075192766267392.
*/
function getDatastore(data, resouceType) {
var deferred = Q.defer();
try {
var keys = getKeysFromRequestData(data, resouceType);
datastore.get(keys, function(err, entities) {
if (err) {
console.error(err);
sentryClient.captureMessage(err);
deferred.reject(new Error(err));
}
// The get operation will not fail for a non-existent entities, it just
// returns null.
if (!entities) {
var error = 'Entity does not exist';
console.error(error);
sentryClient.captureMessage(error);
deferred.reject(new Error(error));
}
deferred.resolve(entities);
});
} catch (err) {
console.error(err);
sentryClient.captureMessage(err);
deferred.reject(new Error(err));
}
return deferred.promise;
}
/**
* Format a contact for ES sync
*
* @param {Object} contactData Contact details from datastore.
*/
function formatESContact(contactId, contactData) {
contactData['Id'] = contactId;
if ('CustomFields.Name' in contactData && 'CustomFields.Value' in contactData) {
// Populate a column for contactData
contactData['CustomFields'] = [];
for (var i = contactData['CustomFields.Name'].length - 1; i >= 0; i--) {
var singleData = {};
singleData.Name = contactData['CustomFields.Name'][i];
singleData.Value = contactData['CustomFields.Value'][i];
contactData['CustomFields'].push(singleData);
}
// Remove the name and value fields
delete contactData['CustomFields.Name'];
delete contactData['CustomFields.Value'];
}
return contactData;
}
/**
* Add a contact to ES
*
* @param {Object} contactData Contact details from datastore.
* Returns true if adding data works and false if not.
*/
function addToElastic(contacts) {
var deferred = Q.defer();
var esActions = [];
for (var i = contacts.length - 1; i >= 0; i--) {
var contactId = contacts[i].key.id;
var contactData = contacts[i].data;
var postContactData = formatESContact(contactId, contactData);
var indexRecord = {
index: {
_index: 'contacts',
_type: 'contact_v2',
_id: contactId
}
};
var dataRecord = postContactData;
esActions.push(indexRecord);
esActions.push({
data: dataRecord
});
}
client.bulk({
body: esActions
}, function(error, response) {
if (error) {
sentryClient.captureMessage(error);
deferred.reject(false);
}
deferred.resolve(true);
});
return deferred.promise;
}
/**
* Syncs a contact information to elasticsearch.
*
* @param {Object} contact Contact details from datastore.
*/
function getAndSyncElastic(contacts) {
var deferred = Q.defer();
addToElastic(contacts).then(function(status) {
if (status) {
deferred.resolve(true);
} else {
deferred.resolve(false);
}
});
return deferred.promise;
}
function removeContactFromElastic(contactId) {
var deferred = Q.defer();
var esActions = [];
var eachRecord = {
delete: {
_index: 'contacts',
_type: 'contact_v2',
_id: contactId
}
};
esActions.push(eachRecord);
client.bulk({
body: esActions
}, function(error, response) {
if (error) {
deferred.resolve(false);
} else {
deferred.resolve(true);
}
});
return deferred.promise;
}
function syncContact(data) {
var deferred = Q.defer();
if (data.Method && data.Method.toLowerCase() === 'create') {
getDatastore(data, 'Contact').then(function(contacts) {
if (contacts != null) {
getAndSyncElastic(contacts).then(function(elasticResponse) {
if (elasticResponse) {
deferred.resolve('Success!');
} else {
var error = 'Elastic sync failed';
sentryClient.captureMessage(error);
deferred.reject(new Error(error));
throw new Error(error);
}
});
} else {
var error = 'Contact not found';
sentryClient.captureMessage(error);
deferred.reject(new Error(error));
throw new Error(error);
}
}, function(error) {
sentryClient.captureMessage(error);
deferred.reject(new Error(error));
throw new Error(error);
});
} else if (data.Method && data.Method.toLowerCase() === 'delete') {
if (!data.Id) {
throw new Error("Id not provided. Make sure you have a 'Id' property " +
"in your request");
}
var contactId = parseInt(data.Id, 10);
removeContactFromElastic(contactId).then(function(elasticResponse) {
if (elasticResponse) {
deferred.resolve('Success!');
} else {
var error = 'Elastic removal failed for ' + data.Id;
sentryClient.captureMessage(error);
deferred.reject(new Error(error));
throw new Error(error);
}
});
} else {
// This case should never happen unless wrong pub/sub method is called.
var error = 'Can not parse method ' + data.Method;
sentryClient.captureMessage(error);
deferred.reject(new Error(error));
throw new Error(error);
}
return deferred.promise;
}
// Subscribe to Pub/Sub for this particular topic
function subscribe(cb) {
var subscription;
// Event handlers
function handleMessage(message) {
cb(null, message);
}
function handleError(err) {
sentryClient.captureMessage(err);
console.error(err);
}
getTopic(topicName, function(err, topic) {
if (err) {
return cb(err);
}
topic.subscribe(subscriptionName, {
autoAck: true,
reuseExisting: true
}, function(err, sub) {
if (err) {
return cb(err);
}
subscription = sub;
// Listen to and handle message and error events
subscription.on('message', handleMessage);
subscription.on('error', handleError);
console.log('Listening to ' + topicName +
' with subscription ' + subscriptionName);
});
});
// Subscription cancellation function
return function() {
if (subscription) {
// Remove event listeners
subscription.removeListener('message', handleMessage);
subscription.removeListener('error', handleError);
subscription = undefined;
}
};
}
// Begin subscription
subscribe(function(err, message) {
// Any errors received are considered fatal.
if (err) {
sentryClient.captureMessage(err);
console.error(err);
throw err;
}
console.log('Received request to process list process ' + message.data.Id);
syncContact(message.data)
.then(function(status) {
rp('https://hchk.io/f0add847-7c16-4753-994c-2943676303cb')
.then(function(htmlString) {
console.log('Completed execution for ' + message.data.Id);
})
.catch(function(err) {
console.error(err);
});
}, function(error) {
sentryClient.captureMessage(error);
console.error(error);
});
});