-
Notifications
You must be signed in to change notification settings - Fork 103
/
transform.js
390 lines (365 loc) · 12.9 KB
/
transform.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/* eslint-disable no-nested-ternary */
/* eslint-disable no-underscore-dangle */
/* eslint-disable array-callback-return */
const get = require('get-value');
const { ConfigurationError, InstrumentationError } = require('@rudderstack/integrations-lib');
const { EventType, WhiteListedTraits, MappedToDestinationKey } = require('../../../constants');
const {
CONFIG_CATEGORIES,
BASE_ENDPOINT,
MAPPING_CONFIG,
ecomExclusionKeys,
ecomEvents,
eventNameMapping,
jsonNameMapping,
} = require('./config');
const {
createCustomerProperties,
subscribeUserToList,
populateCustomFieldsFromTraits,
batchSubscribeEvents,
getIdFromNewOrExistingProfile,
profileUpdateResponseBuilder,
} = require('./util');
const {
defaultRequestConfig,
constructPayload,
getFieldValueFromMessage,
defaultPostRequestConfig,
extractCustomFields,
removeUndefinedAndNullValues,
isEmptyObject,
addExternalIdToTraits,
adduserIdFromExternalId,
getSuccessRespEvents,
handleRtTfSingleEventError,
flattenJson,
isNewStatusCodesAccepted,
} = require('../../util');
const { JSON_MIME_TYPE, HTTP_STATUS_CODES } = require('../../util/constant');
/**
* Main Identify request handler func
* The function is used to create/update new users and also for adding/subscribing
* users to the list.
* DOCS: 1. https://developers.klaviyo.com/en/v2023-02-22/reference/create_profile
* 2. https://developers.klaviyo.com/en/v2023-02-22/reference/update_profile
* 3. https://developers.klaviyo.com/en/v2023-02-22/reference/subscribe_profiles
* @param {*} message
* @param {*} category
* @param {*} destination
* @param {*} reqMetadata
* @returns
*/
const identifyRequestHandler = async (message, category, destination, reqMetadata) => {
// If listId property is present try to subscribe/member user in list
const { privateApiKey, enforceEmailAsPrimary, listId, flattenProperties } = destination.Config;
const mappedToDestination = get(message, MappedToDestinationKey);
if (mappedToDestination) {
addExternalIdToTraits(message);
adduserIdFromExternalId(message);
}
const traitsInfo = getFieldValueFromMessage(message, 'traits');
let propertyPayload = constructPayload(message, MAPPING_CONFIG[category.name]);
// Extract other K-V property from traits about user custom properties
let customPropertyPayload = {};
customPropertyPayload = extractCustomFields(
message,
customPropertyPayload,
['traits', 'context.traits'],
WhiteListedTraits,
);
propertyPayload = removeUndefinedAndNullValues(propertyPayload);
if (enforceEmailAsPrimary) {
if (!propertyPayload.email && !propertyPayload.phone_number) {
throw new InstrumentationError('None of email and phone are present in the payload');
}
delete propertyPayload.external_id;
customPropertyPayload = {
...customPropertyPayload,
_id: getFieldValueFromMessage(message, 'userId'),
};
}
const data = {
type: 'profile',
attributes: {
...propertyPayload,
properties: removeUndefinedAndNullValues(customPropertyPayload),
},
};
// if flattenProperties is enabled from UI, flatten the user properties
data.attributes.properties = flattenProperties
? flattenJson(data.attributes.properties, '.', 'normal', false)
: data.attributes.properties;
if (isEmptyObject(data.attributes.properties)) {
delete data.attributes.properties;
}
const payload = {
data: removeUndefinedAndNullValues(data),
};
const endpoint = `${BASE_ENDPOINT}${category.apiUrl}`;
const requestOptions = {
headers: {
Authorization: `Klaviyo-API-Key ${privateApiKey}`,
accept: JSON_MIME_TYPE,
'content-type': JSON_MIME_TYPE,
revision: '2023-02-22',
},
};
const { profileId, response, statusCode } = await getIdFromNewOrExistingProfile(
endpoint,
payload,
requestOptions,
);
const responseMap = {
profileUpdateResponse: profileUpdateResponseBuilder(
payload,
profileId,
category,
privateApiKey,
),
};
// check if user wants to subscribe profile or not and listId is present or not
if (traitsInfo?.properties?.subscribe && (traitsInfo.properties?.listId || listId)) {
responseMap.subscribeUserToListResponse = subscribeUserToList(message, traitsInfo, destination);
}
if (isNewStatusCodesAccepted(reqMetadata) && statusCode === HTTP_STATUS_CODES.CREATED) {
responseMap.suppressEventResponse = {
...responseMap.profileUpdateResponse,
statusCode: HTTP_STATUS_CODES.SUPPRESS_EVENTS,
error: JSON.stringify(response),
};
return responseMap.subscribeUserToListResponse
? [responseMap.subscribeUserToListResponse]
: responseMap.suppressEventResponse;
}
return responseMap.subscribeUserToListResponse
? [responseMap.profileUpdateResponse, responseMap.subscribeUserToListResponse]
: responseMap.profileUpdateResponse;
};
// ----------------------
// Main handler func for track request/screen request
// User info needs to be mapped to a track event (mandatory)
// DOCS: https://developers.klaviyo.com/en/v2023-02-22/reference/create_event
// ----------------------
const trackRequestHandler = (message, category, destination) => {
const payload = {};
const { privateApiKey, flattenProperties } = destination.Config;
let event = get(message, 'event');
if (event && typeof event !== 'string') {
throw new InstrumentationError('Event type should be a string');
}
event = event ? event.trim().toLowerCase() : event;
let attributes = {};
if (ecomEvents.includes(event) && message.properties) {
const eventName = eventNameMapping[event];
const eventMap = jsonNameMapping[eventName];
attributes.metric = { name: eventName };
const categ = CONFIG_CATEGORIES[eventMap];
attributes.properties = constructPayload(message.properties, MAPPING_CONFIG[categ.name]);
// products mapping using Items.json
// mapping properties.items to payload.properties.items and using properties.products as a fallback to properties.items
// properties.items is to be deprecated soon
if (message.properties?.products || message.properties?.items) {
const items = message.properties.items || message.properties.products;
const itemArr = [];
if (Array.isArray(items)) {
items.forEach((key) => {
let item = constructPayload(key, MAPPING_CONFIG[CONFIG_CATEGORIES.ITEMS.name]);
item = removeUndefinedAndNullValues(item);
if (!isEmptyObject(item)) {
itemArr.push(item);
}
});
}
if (!attributes.properties) {
payload.properties = {};
}
if (itemArr.length > 0) {
attributes.properties.items = itemArr;
}
}
// all extra props passed is incorporated inside properties
let customProperties = {};
customProperties = extractCustomFields(
message,
attributes.customProperties,
['properties'],
ecomExclusionKeys,
);
if (!isEmptyObject(customProperties)) {
attributes.properties = {
...attributes.properties,
...customProperties,
};
}
if (isEmptyObject(attributes.properties)) {
delete payload.properties;
}
} else {
const value =
message.properties?.revenue || message.properties?.total || message.properties?.value;
attributes = constructPayload(message, MAPPING_CONFIG[category.name]);
if (value) {
attributes.value = value;
}
}
// if flattenProperties is enabled from UI, flatten the event properties
attributes.properties = flattenProperties
? flattenJson(attributes.properties, '.', 'normal', false)
: attributes.properties;
// Map user properties to profile object
attributes.profile = {
...createCustomerProperties(message, destination.Config),
...populateCustomFieldsFromTraits(message),
};
attributes.profile = flattenProperties
? flattenJson(attributes.profile, '.', 'normal', false)
: attributes.profile;
if (message.timestamp) {
attributes.time = message.timestamp;
}
payload.data = { type: 'event' };
payload.data.attributes = attributes;
const response = defaultRequestConfig();
response.endpoint = `${BASE_ENDPOINT}${category.apiUrl}`;
response.method = defaultPostRequestConfig.requestMethod;
response.headers = {
Authorization: `Klaviyo-API-Key ${privateApiKey}`,
'Content-Type': JSON_MIME_TYPE,
Accept: JSON_MIME_TYPE,
revision: '2023-02-22',
};
response.body.JSON = removeUndefinedAndNullValues(payload);
return response;
};
// ----------------------
// Main handlerfunc for group request
// we will add/subscribe users to the list
// based on property sent
// DOCS: https://developers.klaviyo.com/en/v2023-02-22/reference/subscribe_profiles
// ----------------------
const groupRequestHandler = (message, category, destination) => {
if (!message.groupId) {
throw new InstrumentationError('groupId is a required field for group events');
}
if (!message.traits.subscribe) {
throw new InstrumentationError('Subscribe flag should be true for group call');
}
const traitsInfo = getFieldValueFromMessage(message, 'traits');
let response;
if (traitsInfo?.subscribe) {
response = subscribeUserToList(message, traitsInfo, destination);
}
return [response];
};
// Main event processor using specific handler funcs
const processEvent = async (message, destination, reqMetadata) => {
if (!message.type) {
throw new InstrumentationError('Event type is required');
}
if (!destination.Config.privateApiKey) {
throw new ConfigurationError(`Private API Key is a required field for ${message.type} events`);
}
const messageType = message.type.toLowerCase();
let category;
let response;
switch (messageType) {
case EventType.IDENTIFY:
category = CONFIG_CATEGORIES.IDENTIFY;
response = await identifyRequestHandler(message, category, destination, reqMetadata);
break;
case EventType.SCREEN:
case EventType.TRACK:
category = CONFIG_CATEGORIES.TRACK;
response = trackRequestHandler(message, category, destination);
break;
case EventType.GROUP:
category = CONFIG_CATEGORIES.GROUP;
response = groupRequestHandler(message, category, destination);
break;
default:
throw new InstrumentationError(`Event type ${messageType} is not supported`);
}
return response;
};
const process = async (event, reqMetadata) => {
const result = await processEvent(event.message, event.destination, reqMetadata);
return result;
};
// This function separates subscribe response and other responses in chunks
const getEventChunks = (event, subscribeRespList, nonSubscribeRespList) => {
if (Array.isArray(event.message)) {
// this list contains responses for subscribe endpoint
subscribeRespList.push(event);
} else {
// this list doesn't contain subsribe endpoint responses
nonSubscribeRespList.push(event);
}
};
const processRouterDest = async (inputs, reqMetadata) => {
let batchResponseList = [];
const batchErrorRespList = [];
const subscribeRespList = [];
const nonSubscribeRespList = [];
const { destination } = inputs[0];
await Promise.all(
inputs.map(async (event) => {
try {
if (event.message.statusCode) {
// already transformed event
getEventChunks(
{ message: event.message, metadata: event.metadata, destination },
subscribeRespList,
nonSubscribeRespList,
);
} else {
// if not transformed
getEventChunks(
{
message: await process(event, reqMetadata),
metadata: event.metadata,
destination,
},
subscribeRespList,
nonSubscribeRespList,
);
}
} catch (error) {
const errRespEvent = handleRtTfSingleEventError(event, error, reqMetadata);
batchErrorRespList.push(errRespEvent);
}
}),
);
const batchedSubscribeResponseList = [];
if (subscribeRespList.length > 0) {
const batchedResponseList = batchSubscribeEvents(subscribeRespList);
batchedSubscribeResponseList.push(...batchedResponseList);
}
const nonSubscribeSuccessList = nonSubscribeRespList.map((resp) => {
const response = resp;
const { message, metadata, destination: eventDestination } = response;
if (
isNewStatusCodesAccepted(reqMetadata) &&
message?.statusCode &&
message.statusCode === HTTP_STATUS_CODES.SUPPRESS_EVENTS
) {
const { error } = message;
delete message.error;
delete message.statusCode;
return {
...getSuccessRespEvents(
message,
[metadata],
eventDestination,
false,
HTTP_STATUS_CODES.SUPPRESS_EVENTS,
),
error,
};
}
return getSuccessRespEvents(message, [metadata], eventDestination);
});
batchResponseList = [...batchedSubscribeResponseList, ...nonSubscribeSuccessList];
return [...batchResponseList, ...batchErrorRespList];
};
module.exports = { process, processRouterDest };