-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
94 lines (79 loc) · 2.03 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
const ITEM_REGEX = /[a-zA-Z0-9]+\.(png|jpe?g|gifv?)/;
addEventListener('fetch', event => {
const method = event.request.method;
if (method !== 'GET') {
event.respondWith(new Response('', {
status: 204,
}));
return;
}
event.respondWith(handleRequest(event));
})
/**
* Respond to the request
* @param {FetchEvent} event
*/
async function handleRequest (event) {
const request = event.request;
const url = new URL(request.url);
const path = url.pathname.substring(1);
if (!path) {
return jsonError('Missing input', 406);
}
if (!ITEM_REGEX.test(path)) {
return jsonError('Not found', 404);
}
return fetchImgurImage(path, event);
}
/**
* Fetch an image with the id
* @param {String} imageId
* @param {FetchEvent} event
* @return Response
*/
async function fetchImgurImage(imageId, event) {
const lookUpUrl = getImageFetchUrl(imageId);
const cache = caches.default;
// const request = event.request;
// let response = await cache.match(request);
let response = await cache.match(lookUpUrl);
if (!response) {
const imageResponse = await fetch(lookUpUrl, {
headers: {
'User-Agent': process.env.USER_AGENT,
}
});
const headers = {
'cache-control': 'public, max-age=14400', // 4 hours in seconds
};
const cloned = imageResponse.clone();
response = new Response(cloned.body, { ...cloned, headers });
// only cache 200 responses
if (imageResponse.status === 200) {
// event.waitUntil(cache.put(request, imageResponse.clone()));
event.waitUntil(cache.put(lookUpUrl, imageResponse.clone()));
}
}
return response;
}
/**
* Fetch an image with the id
* @param {String} imageId
* @return String
*/
function getImageFetchUrl(imageId) {
return process.env.PHOTO_DOMAIN + imageId;
}
function jsonError(message, status = 400) {
return new Response(
JSON.stringify({
error: message
}),
{
status: status,
headers: {
'content-type': 'application/json'
}
}
);
}