-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathindex.js
56 lines (49 loc) · 1.54 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
/*global CUSTOM_HEADER*/
/*global ALLOWED_ORIGINS*/
import ImageComponents from './src/imageComponents'
import ResizerOptions from './src/resizerOptions'
addEventListener('fetch', (event) => {
/* Get the origin image if the request is from the resizer worker itself */
if (/image-resizing/.test(event.request.headers.get('via'))) {
event.respondWith(fetch(event.request))
} else {
event.respondWith(handleRequest(event.request))
}
})
async function handleRequest(request) {
try {
/* ALLOWED_ORIGINS is a comma-separated string of hostnames */
const imgComponents = new ImageComponents(
request,
ALLOWED_ORIGINS.split(','),
CUSTOM_HEADER
)
if (!imgComponents.isResizeAllowed()) {
return fetch(request)
}
const imageResizerOptions = new ResizerOptions(
request.headers,
imgComponents.getSize(),
imgComponents.getExtension()
)
const imageRequest = new Request(imgComponents.getUnsizedUrl(), {
headers: request.headers,
})
if (imgComponents.hasCustomHeader()) {
imageRequest.headers.append(
imgComponents.getCustomHeader('name'),
imgComponents.getCustomHeader('value')
)
}
const response = await fetch(imageRequest, imageResizerOptions.getOptions())
if (response.ok) {
return response
} else {
console.log('Image resizing failed: ' + response.status)
return response
}
} catch (err) {
console.log('Error fetching image: ' + err)
return new Response('Error fetching image', { status: 500 })
}
}