-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
249 lines (239 loc) · 6.73 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
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
const API_URL =
'http://datamall2.mytransport.sg/ltaodataservice/PCDRealTime?TrainLine=';
const API_FORECAST_URL =
'http://datamall2.mytransport.sg/ltaodataservice/PCDForecast?TrainLine=';
const trainCodes = [
'CCL',
'CEL',
'CGL',
'DTL',
'EWL',
'NEL',
'NSL',
'BPL',
'SLRT',
'PLRT',
];
let apiKeyIndex = 0;
const apiKey = () => {
const KEYS = LTA_DATAMALL_ACCOUNT_KEY.split(' ');
apiKeyIndex = (apiKeyIndex + 1) % KEYS.length;
console.log('API key index', apiKeyIndex);
return KEYS[apiKeyIndex];
};
const apiFetch = async url => {
console.log('🥏 ' + url);
try {
const response = await fetch(url, {
headers: {
accept: 'application/json',
AccountKey: apiKey(),
},
}).then(res => res.json());
if (response.fault) {
throw new Error(response.fault);
}
return response;
} catch (e) {
console.log('♻️ ' + url);
const response = await fetch(url, {
headers: {
accept: 'application/json',
AccountKey: apiKey(),
},
}).then(res => res.json());
return response;
}
};
// https://stackoverflow.com/a/26215431
function toCamel(o) {
var newO, origKey, newKey, value;
if (o instanceof Array) {
return o.map(function(value) {
if (typeof value === 'object') {
value = toCamel(value);
}
return value;
});
} else {
newO = {};
for (origKey in o) {
if (o.hasOwnProperty(origKey)) {
newKey = (
origKey.charAt(0).toLowerCase() + origKey.slice(1) || origKey
).toString();
value = o[origKey];
if (
value instanceof Array ||
(value !== null && value.constructor === Object)
) {
value = toCamel(value);
}
newO[newKey] = value;
}
}
}
return newO;
}
function handleOptions(request) {
// Make sure the necessary headers are present
// for this to be a valid pre-flight request
let headers = request.headers;
if (
headers.get('Origin') !== null &&
headers.get('Access-Control-Request-Method') !== null &&
headers.get('Access-Control-Request-Headers') !== null
) {
// Handle CORS pre-flight request.
// If you want to check or reject the requested method + headers
// you can do that here.
let respHeaders = {
...corsHeaders,
// Allow all future content Request headers to go back to browser
// such as Authorization (Bearer) or X-Client-Name-Version
'Access-Control-Allow-Headers': request.headers.get(
'Access-Control-Request-Headers',
),
};
return new Response(null, {
headers: respHeaders,
});
} else {
// Handle standard OPTIONS request.
// If you want to allow other HTTP Methods, you can do that here.
return new Response(null, {
headers: {
Allow: 'GET, HEAD, POST, OPTIONS',
},
});
}
}
async function eventHandler(event) {
const url = new URL(event.request.url);
const { pathname } = url;
console.log('🚃 ' + pathname);
let response;
switch (pathname) {
case '/favicon.ico': {
return new Response(null, { status: 204 });
}
case '/testForecast': {
const data = await apiFetch(API_FORECAST_URL + 'CCL');
const bin = await fetch('https://httpbin.org/get').then(res =>
res.json(),
);
const response = new Response(JSON.stringify({ data, bin }));
response.headers.set('Content-Type', 'application/json');
return response;
}
case '/forecast': {
const results = JSON.parse(await CACHE.get('forecast')) || [];
const errors = [];
let cacheHit = true;
if (!results || !results.length) {
cacheHit = false;
const responses = await Promise.allSettled(
trainCodes.map((code, i) => {
return new Promise(resolve => setTimeout(resolve, 2000 * i)).then(
() => {
return apiFetch(API_FORECAST_URL + code);
},
);
}),
);
responses
.filter(res => res.status === 'fulfilled')
.forEach(res => {
const { value, fault } = res.value;
if (fault) {
errors.push(fault.detail.errorcode);
return;
}
const result = value.map(obj => toCamel(obj));
results.push(...result);
});
if (!errors.length) {
// Tomorrow at 12AM SGT timezone, in epoch seconds
const expiration = new Date(
new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000,
).getTime();
event.waitUntil(
CACHE.put('forecast', JSON.stringify(results), {
expiration,
}),
);
}
}
response = new Response(
JSON.stringify({
data: results,
meta: {
count: results.length,
errors,
},
}),
);
response.headers.set('Cache-Control', 'public, max-age=3600'); // 1 hour
response.headers.set('x-kv-cache', cacheHit ? 'HIT' : 'MISS');
break;
}
case '/': {
const results = JSON.parse(await CACHE.get('realtime')) || [];
const errors = [];
let cacheHit = true;
if (!results || !results.length) {
cacheHit = false;
const responses = await Promise.allSettled(
trainCodes.map(code => {
return apiFetch(API_URL + code);
}),
);
responses
.filter(res => res.status === 'fulfilled')
.forEach(res => {
const { value, fault } = res.value;
if (fault) {
errors.push(fault.detail.errorcode);
return;
}
const result = value.map(obj => toCamel(obj));
results.push(...result);
});
if (!errors.length) {
event.waitUntil(
CACHE.put('realtime', JSON.stringify(results), {
expirationTtl: 300,
}),
);
}
}
response = new Response(
JSON.stringify({
data: results,
meta: {
count: results.length,
errors,
},
}),
);
response.headers.set('cache-control', 'public, max-age=60'); // 1 min
response.headers.set('x-kv-cache', cacheHit ? 'HIT' : 'MISS');
break;
}
default: {
response = new Response(null, { status: 404 });
}
}
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.append('Vary', 'Origin');
return response;
}
addEventListener('fetch', event => {
const request = event.request;
if (request.method === 'OPTIONS') {
// Handle CORS preflight requests
event.respondWith(handleOptions(request));
} else {
event.respondWith(eventHandler(event));
}
});