-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.js
66 lines (51 loc) · 1.85 KB
/
worker.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
import { allowList, endpoints, cacheDurationSeconds } from './config.js';
import { handleSource } from './handler.js';
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request, allowList))
})
async function handleRequest(request, allowList) {
try {
const url = new URL(request.url);
const apiUrl = url.searchParams.get('api');
// Handle hostname or IP checking
const sourceAllowed = handleSource(request, allowList);
if (sourceAllowed) {
return sourceAllowed;
}
const endpoint = endpoints.find(e => e.url === apiUrl);
if (!endpoint) {
throw new Error('Invalid API URL');
}
const cache = caches.default;
let response = await cache.match(request);
// Delete the api param so it is omitted from the final request
url.searchParams.delete('api');
// Create a proxied request
let req = new Request(apiUrl + url.search, {
method: request.method,
headers: request.headers,
body: request.body,
});
req.headers.set('Authorization', `Bearer ${process.env[endpoint.key]}`);
if (request.method === 'GET' && !response) {
response = await fetch(req);
if (!response.ok) {
throw new Error(`Failed to fetch from API: ${response.statusText}`);
}
let responseClone = response.clone();
responseClone.headers.append('Cache-Control', `public, max-age=${cacheDurationSeconds}`);
// Cache the response without waiting for it to complete
cache.put(request, responseClone).catch(e => {
console.error('Failed to cache response:', e);
});
} else {
response = await fetch(req);
if (!response.ok) {
throw new Error(`Failed to fetch from API: ${response.statusText}`);
}
}
return response;
} catch (err) {
return new Response(err.message, { status: 500 });
}
}