-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.js
47 lines (39 loc) · 1.17 KB
/
middleware.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
import { serveResource } from './src_api/app.js';
export const config = {
// runtime: 'edge', // this is a pre-requisite
// regions: ['sin1'], // only execute this function on iad1
};
const next = () => void 0;
export default async function middleware(request) {
const _parsedUrl = new URL(request.url)
if (_parsedUrl.pathname.slice(0, 5) !== '/api/') {
return next()
}
const req = {
_parsedUrl,
method: request.method,
headers: [...request.headers].reduce((prev, [key, value]) => (prev[key] = value, prev), {}),
on(type, fn) {
if (type === 'data') {
request.text().then(data => {
fn(data)
})
}
else if (type === 'end') {
// setTimeout(fn, 100)
setTimeout(_ => { fn() }, 100)
}
}
}
const headers = {};
const res = {
setHeader(key, value) {
headers[key] = value;
},
end(data) {
this.data = data;
},
}
await serveResource(req, res, next)
return new Response(res.data, { status: res.statusCode || 500, headers })
}