-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
210 lines (186 loc) · 5 KB
/
index.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
var http = require('http');
var dispatcher = require('httpdispatcher');
var $http_request = require('request');
const SERVER_PORT = 8080;
const ZAPIER_URL = "https://zapier.com/hooks/catch/39fju3/";
var accessToken;
function onRequest(request, response){
try {
console.log("[Request] URL:" + request.url);
dispatcher.dispatch(request, response);
} catch(err) {
console.log("[Error] " + err);
}
}
function setupServer()
{
var server = http.createServer(onRequest);
server.listen(SERVER_PORT, function(){
console.log("Server listening on: http://localhost:%s", SERVER_PORT);
});
}
function extend(target) {
var sources = [].slice.call(arguments, 1);
sources.forEach(function (source) {
for (var prop in source) {
target[prop] = source[prop];
}
});
return target;
}
function requestAuthTicket(callback)
{
$http_request.post(
{
headers: {
'Content-Type': 'application/json'
},
uri: 'https://home.mozu.com/api/platform/applications/authtickets',
form: {
'ApplicationId': 'nov14bc1.codepens.1.0.0.release',
'SharedSecret': '7dcebef81ef34c059611f8de796b801d'
}
},
function(error, res, body)
{
if(error)
{
console.log("[Error] Error getting auth ticket: " + body)
}
else
{
parsedBody = JSON.parse(body);
accessToken = parsedBody["accessToken"];
callback();
}
}
)
}
function requestProductDetails(extraHeaders, entityId, rootURL, callback, errorCallback)
{
var finalURL = "https://" + rootURL + "/api/commerce/catalog/storefront/products/" + entityId + "?contextLevel=Site";
console.log("[INFO] Final URL: " + finalURL);
var requestHeader =
{
'x-vol-app-claims': accessToken
};
var finalHeaders = extend({}, extraHeaders, requestHeader)
$http_request( { headers: finalHeaders, uri: finalURL, method: "GET" },
function(error, response, body)
{
if(!error && response.statusCode == 200)
{
console.log("[INFO] Good result from server");
callback(JSON.parse(body));
}
else
{
console.log("[Error] GET returned: " + response.statusCode + " - " + body);
errorCallback(response.statusCode, body);
}
}
);
}
function zap(data, callback, errorCallback)
{
$http_request( { headers: {'Content-Type': 'text/json'}, uri: ZAPIER_URL, method: "POST", form: data },
function(error, response, body)
{
if(!error && response.statusCode == 200)
{
console.log("[INFO] Zap succeeded");
callback(body);
}
else
{
console.log("[Error] GET returned: " + response.statusCode + " - " + body);
errorCallback(response.statusCode, body);
}
}
);
}
function zapProduct(req, successCallback, errorCallback)
{
var formData = JSON.parse(req.body);
var entityId = formData.entityId;
var storeURL = req.headers["x-vol-tenant-domain"];
var topic = formData.topic;
console.log("[INFO] Entity ID: " + entityId);
console.log("[INFO] Server: " + storeURL);
var specialHeaders = {}
for(var headerName in req.headers)
{
if(headerName.indexOf("x-vol") != -1)
{
specialHeaders[headerName] = req.headers[headerName];
}
}
requestProductDetails(
specialHeaders,
entityId,
storeURL,
function productCallback(data)
{
zap_info =
{
"mozu-tenant": req.headers["x-vol-tenant"],
"mozu-site": req.headers["v-vol-site"],
"mozu-action": topic,
"data": data
}
zap(
zap_info,
function(zap_result)
{
successCallback(JSON.stringify(data));
},
function onError(code, message)
{
errorCallback(code, message)
}
);
},
function onError(code, message)
{
errorCallback(code, message)
}
);
}
requestAuthTicket(function()
{
console.log("[INFO] Got access token: " + accessToken);
setupServer();
});
dispatcher.onPost("/trigger", requestAndSendProduct);
function requestAndSendProduct(req, res, isRetry) {
if(isRetry === undefined)
isRetry = false;
zapProduct(
req,
function onSuccess()
{
res.writeHead(200, {'Content-Type': 'text/json'});
res.end("{success: true}");
},
function onError(code, message)
{
console.log("[Error]");
var errorData = JSON.parse(message);
var errorCode = (errorData.items[0] === undefined) ? "" : errorData.items[0].errorCode;
if(code == 401 && errorCode == "INVALID_ACCESS_TOKEN" && !isRetry)
{
console.log("[INFO] Discarding expired auth token");
//If the result from the server says that we have an invalid access token, we go grab a new one
requestAuthTicket(function()
{
requestAndSendProduct(req, res, true);
});
}
else
{
res.writeHead(500, {'Content-Type': 'text/json'});
res.end(message);
}
}
);
}