-
Notifications
You must be signed in to change notification settings - Fork 67
/
index.js
82 lines (77 loc) · 2.22 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
import Router from './router'
import { handleVerify } from './handlers/verify'
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,HEAD,POST,OPTIONS',
'Access-Control-Max-Age': '86400',
}
function handleOptions(request) {
let headers = request.headers
if (
headers.get('Origin') !== null &&
headers.get('Access-Control-Request-Method') !== null &&
headers.get('Access-Control-Request-Headers') !== null
) {
let respHeaders = {
...corsHeaders,
'Access-Control-Allow-Headers': request.headers.get(
'Access-Control-Request-Headers'
),
}
return new Response(null, {
headers: respHeaders,
})
} else {
return new Response(null, {
headers: {
Allow: 'GET, HEAD, POST, OPTIONS',
},
})
}
}
async function handleRequest(request) {
const r = new Router()
r.get('.*/verify', request => handleVerify(request))
r.get(
'/',
() =>
new Response(null, {
status: 404,
statusText: 'No route specified',
})
)
const resp = await r.route(request)
return resp
}
const PROXY_ENDPOINT = '/api'
addEventListener('fetch', event => {
const request = event.request
const url = new URL(request.url)
if (url.pathname.startsWith(PROXY_ENDPOINT)) {
if (request.method === 'OPTIONS') {
// Handle CORS preflight requests
event.respondWith(handleOptions(request))
} else if (
request.method === 'GET' ||
request.method === 'HEAD' ||
request.method === 'POST'
) {
// Handle requests to the API server
event.respondWith(handleRequest(request))
} else {
event.respondWith(
new Response(null, {
status: 405,
statusText: 'Method Not Allowed',
})
)
}
} else {
event.respondWith(
new Response(null, {
status: 404,
statusText: 'Invalid route',
})
)
}
})