-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.mjs
80 lines (67 loc) · 1.91 KB
/
server.mjs
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
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import express from 'express';
import { createServer as createViteServer } from 'vite';
import { compileHtml } from './build/utils.mjs';
import { availableLanguages, DEFAULT_LANG, i18n } from './build/i18n-utils.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
async function createServer() {
const app = express();
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'custom',
});
app.use(vite.middlewares);
app.use(i18n.init);
app.use('*', async (req, res, next) => {
req.setLocale(getLocaleFromReq(req));
process.env.locale = getLocaleFromReq(req);
const url = getFixedUrl(req);
if (!url.endsWith('.html')) {
return res.redirect(removeLanguagesFromUrl(req.originalUrl));
}
try {
let template = fs.readFileSync(
path.resolve(__dirname, 'src', url),
'utf-8'
);
const html = compileHtml(template, {
...res.locals,
});
res
.status(200)
.set({ 'Content-Type': 'text/html' })
.end(await vite.transformIndexHtml(url, html));
} catch (e) {
vite.ssrFixStacktrace(e);
next(e);
}
});
const url = new URL(process.env.BASE_DOMAIN);
app.listen(url.port);
}
createServer().then(() => {
console.log('App is running on: ', process.env.BASE_DOMAIN);
});
function getLocaleFromReq(req) {
let locale = DEFAULT_LANG;
const parts = req.originalUrl.split('/');
if (availableLanguages.includes(parts[1])) {
locale = parts[1];
}
return locale;
}
function getFixedUrl(req) {
let url = removeLanguagesFromUrl(req.originalUrl).replace('/', '');
if (!url) {
url = 'index.html';
}
return url;
}
function removeLanguagesFromUrl(originalUrl) {
return originalUrl.replace(
new RegExp(`^/(${availableLanguages.join('|')})/`),
'/'
);
}