-
Notifications
You must be signed in to change notification settings - Fork 0
/
server-dev.js
99 lines (79 loc) · 2.38 KB
/
server-dev.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//server-dev.js
import fs from 'fs';
import express from 'express';
import morgan from 'morgan';
import { createServer } from 'vite';
import apiRouter from './server/apiRouter.js';
const app = express();
const vite = await createServer({
server: {
middlewareMode: true,
},
appType: 'custom',
});
app.use(morgan('combined'))
if (process.env.DOCKER_PROXY_CAPTURE_FOR_MOCK === 'true') {
function logResponseBody(req, res, next) {
if (req.path.startsWith('/docker') || req.path.startsWith('/api')) {
const origPath = req.path
var oldWrite = res.write,
oldEnd = res.end;
var chunks = [];
res.write = function (chunk) {
chunks.push(Buffer.copyBytesFrom(chunk));
oldWrite.apply(res, arguments);
};
res.end = function (chunk) {
if (chunk)
chunks.push(Buffer.copyBytesFrom(chunk));
var body = Buffer.concat(chunks).toString('utf8');
const path = 'server/mock' + origPath
const dir = path.split('/').slice(0, -1).join('/')
try {
fs.mkdirSync(dir, {recursive: true})
fs.writeFileSync(path, body)
} catch (error) {
console.log(error)
}
oldEnd.apply(res, arguments);
};
}
next();
}
app.use(logResponseBody);
} else if (process.env.DOCKER_PROXY_MOCK === 'true') {
function mockResponseBody(req, res, next) {
if (req.path.startsWith('/docker') || req.path.startsWith('/api')) {
const origPath = req.path
try {
const path = 'server/mock' + origPath
const body = fs.readFileSync(path)
res.status(200).end(body)
} catch (error) {
console.log(error)
}
} else {
next();
}
}
app.use(mockResponseBody);
}
app.use(apiRouter)
app.get('/health', (_, res) => {
res.send('up')
})
app.use(vite.middlewares);
app.use(/.*/, async (req, res) => {
console.log('Getting from ' + req.originalUrl)
const url = req.originalUrl;
try {
const index = await vite.transformIndexHtml(url, fs.readFileSync('index.html', 'utf-8'));
res.status(200).set({ 'Content-Type': 'text/html' }).end(index);
} catch (error) {
console.log(error)
res.status(500).end(error.toString());
}
});
app.listen(4173, () => {
console.log('http://localhost:4173');
});