-
Notifications
You must be signed in to change notification settings - Fork 0
/
ct-cart-api-extension.js
189 lines (174 loc) · 5.7 KB
/
ct-cart-api-extension.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
var https = require('https');
var url = require('url');
var zlib = require('zlib');
var uuid = require('uuid/v1');
// Global constants
const NR_INSERT_KEY = process.env.NR_INSERT_KEY;
const NR_ENDPOINT = process.env.NR_ENDPOINT;
const NR_MAX_RETRIES = process.env.NR_MAX_RETRIES || 3;
const NR_RETRY_INTERVAL = process.env.NR_RETRY_INTERVAL || 2000; // default: 2 seconds
module.exports = async function (context, req) {
// Reject a cart that orders more than 10 items
var cart = req.body.resource.obj;
var itemsTotal = cart.lineItems.reduce((acc, curr) => {
return acc + curr.quantity;
}, 0);
if (itemsTotal == 3) {
context.res = {
status: 400,
body: {
errors: [{
code: "ReferenceExists",
message: "Hello team, nice to meet you!"
}]
}
};
}
else if (itemsTotal == 4) {
//context.log('cart.lineItems[0]: ', JSON.stringify(cart.lineItems[0].id));
const uniqueId = uuid();
//context.log('uniqueId: '+uniqueId);
context.res = {
status: 200,
body: {
actions: [{
action: 'setLineItemCustomType',
"lineItemId": cart.lineItems[0].id,
"type": {
"typeId": "type",
"key": "provider"
},
"fields": {
"provider": "Lufthansa",
"provider-status": "confirmed",
"provider-booking-ref": uniqueId,
},
}]
}
};
}
else if (itemsTotal <= 10) {
context.res = {
status: 200,
body: undefined
};
await forwardToNewRelic(cart, context);
}
else {
context.res = {
status: 400,
body: {
errors: [{
code: "InvalidInput",
message: "You can not put more than 10 items into the cart."
}]
}
};
}
context.done();
};
function compressData(data) {
return new Promise((resolve, reject) => {
zlib.gzip(data, (e, compressedData) => {
if (!e) {
resolve(compressedData);
} else {
reject({ error: e, res: null });
}
});
});
}
async function forwardToNewRelic(payload, context) {
try {
//context.log('payload: ',JSON.stringify(payload));
nrData = []
payload.lineItems.forEach(lineItem => {
lineItemData = {
eventType: 'sunrise' + payload.type,
cartId: payload.id,
cartCustomerId: payload.customerId,
cartTotalPrice: payload.totalPrice.centAmount,
cartProduct: JSON.stringify(lineItem.name.en),
cartProductQuantity: lineItem.quantity,
cartProductPrice: lineItem.price.value.centAmount,
cartCountry: payload.country
};
//context.log('line item: ', JSON.stringify(lineItemData));
nrData.push(lineItemData)
});
compressedPayload = await compressData(JSON.stringify(nrData));
try {
await retryMax(httpSend, NR_MAX_RETRIES, NR_RETRY_INTERVAL, [
compressedPayload,
context,
]);
context.log('Logs payload successfully sent to New Relic');
} catch (e) {
context.log.error(
'Max retries reached: failed to send logs payload to New Relic'
);
context.log.error('Exception: ', JSON.stringify(e));
}
} catch (e) {
context.log.error('Error during payload compression');
context.log.error('Exception: ', JSON.stringify(e));
}
}
function httpSend(data, context) {
return new Promise((resolve, reject) => {
const urlObj = url.parse(NR_ENDPOINT);
const options = {
hostname: urlObj.hostname,
port: 443,
path: urlObj.pathname,
protocol: urlObj.protocol,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Encoding': 'gzip',
'X-Insert-Key': NR_INSERT_KEY
},
};
var req = https.request(options, (res) => {
var body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
body += chunk; // don't really do anything with body
});
res.on('end', () => {
context.log('Got response:' + res.statusCode);
if (res.statusCode === 200) {
resolve(body);
} else {
reject({ error: null, res: res });
}
});
});
req.on('error', (e) => {
context.log('ex:', JSON.stringify(e))
reject({ error: e, res: null });
});
req.write(data);
req.end();
});
}
/**
* Retry with Promise
* fn: the function to try
* retry: the number of retries
* interval: the interval in millisecs between retries
* fnParams: list of params to pass to the function
* @returns A promise that resolves to the final result
*/
function retryMax(fn, retry, interval, fnParams) {
return fn.apply(this, fnParams).catch((err) => {
return retry > 1
? wait(interval).then(() => retryMax(fn, retry - 1, interval, fnParams))
: Promise.reject(err);
});
}
function wait(delay) {
return new Promise((fulfill) => {
setTimeout(fulfill, delay || 0);
});
}