-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes.js
81 lines (75 loc) · 2.25 KB
/
routes.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
import { load } from 'cheerio'
import { Router } from '@edgio/core'
import { isCloud } from '@edgio/core/environment'
import { injectBrowserScript, starterRoutes } from '@edgio/starter'
import responseBodyToString from '@edgio/core/utils/responseBodyToString'
const cachingFeature = {
caching: {
max_age: '1h',
service_worker_max_age: '60s',
stale_while_revalidate: '1d',
ignore_origin_no_cache: [200],
bypass_client_cache: true,
cache_key_query_string: {
include_all_except: ['edgio_dt_pf', 'edgio_prefetch'],
},
},
}
const headersFeature = {
headers: {
remove_origin_response_headers: ['cache-control'],
},
}
export default new Router()
// The default configuration to apply on all routes
.match('/:path*', {
...cachingFeature,
...headersFeature,
origin: {
set_origin: 'origin',
},
})
// Proxy /wiki to origin, transforming the response to inject the browser script and
// rewrite the image URLs to use the /uploads origin for image optimization
.match('/wiki/:path*', ({ proxy }) => {
proxy('origin', {
transformResponse: (res) => {
injectBrowserScript(res)
const $ = load(responseBodyToString(res))
// Replace the domain and append ?auto=webp in img tags src attribute
// for image optimization
$('img').each((index, element) => {
const $img = $(element)
const src = $img.removeAttr('srcset').attr('src')
if (src && src.startsWith('//upload.wikimedia.org/')) {
const modifiedSrc = src.replace(/\/\/upload\.wikimedia\.org\//, '/uploads/')
// Only optimize images running in the Edgio cloud
if (isCloud()) {
$img.attr('src', modifiedSrc + '?auto=webp')
}
}
})
res.body = $.html()
},
})
})
// Proxy images to the upload origin then send them though the Edgio image optimizer
.match('/uploads/:path*', {
...cachingFeature,
origin: {
set_origin: 'upload',
},
response: {
optimize_images: true,
},
url: {
url_rewrite: [
{
source: '/uploads/:path*',
syntax: 'path-to-regexp',
destination: '/:path*',
},
],
},
})
.use(starterRoutes)