-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
69 lines (63 loc) · 1.94 KB
/
server.ts
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
import { setupServer } from 'msw/node';
import { handlers } from './src/handlers';
import http from 'http';
const port = Number(process.env.PORT) || 8000;
(async function runServer() {
const { default: fetch, Headers, Response } = await import('node-fetch');
const mockServer = setupServer(...handlers);
mockServer.listen({
onUnhandledRequest: 'warn',
});
const server = http.createServer(async (req, res) => {
const body: string = await new Promise(res => {
let data = '';
req.on('data', chunk => {
data += chunk;
});
req.on('end', () => {
res(data);
});
});
const headers = new Headers();
for (let header in req.headers) {
headers.append(header, req.headers[header].toString());
}
if (req.method === 'OPTIONS') {
res.writeHead(200, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': '*',
});
res.end('');
return;
}
try {
res.setHeader('access-control-allow-origin', '*');
res.setHeader('access-control-allow-headers', '*');
const requestUrl = `http://localhost:8000${req.url}`;
const response = await fetch(requestUrl, {
method: req.method,
body: req.method !== 'GET' ? body : undefined,
headers,
});
if (!(response instanceof Response)) {
throw new Error('Response is not instance of Response');
}
const result = await response.text();
response.headers.forEach((v, k) => res.setHeader(k, v));
res.statusCode = response.status;
res.end(result);
} catch (err) {
console.error(err);
res.statusCode = 500;
if (err instanceof Error) {
res.end(err.message);
} else {
res.end(err.toString());
}
}
});
server.listen(port, () => {
console.log(`Server running at port ${port}`);
});
})();