index.ts 2.4 KB
Newer Older
1 2
/* eslint-disable no-console */

3
import {config} from 'dotenv';
4
import express from 'express';
5
import path from 'path';
6 7 8
import resolve from 'enhanced-resolve';

config();
9

10
const isDev = process.env.NODE_ENV === 'development';
P
Peter Pan 已提交
11
const isDemo = !!process.env.DEMO;
12

13
const host = process.env.HOST || 'localhost';
14
const port = Number.parseInt(process.env.PORT || '', 10) || 8999;
15
const backend = process.env.BACKEND;
16
const delay = Number.parseInt(process.env.DELAY || '', 10);
17
const publicPath = process.env.PUBLIC_PATH || '/';
18 19
const apiUrl = process.env.API_URL || `${process.env.PUBLIC_PATH || ''}/api`;
const pingUrl = process.env.PING_URL;
P
Peter Pan 已提交
20

21
const root = path.dirname(resolve.sync(__dirname, '@visualdl/core'));
22

23
const app = express();
24

25
async function start() {
26
    if (backend) {
P
Peter Pan 已提交
27
        const {createProxyMiddleware} = await import('http-proxy-middleware');
28 29
        app.use(
            apiUrl,
30 31 32 33 34
            createProxyMiddleware({
                target: backend,
                changeOrigin: true
            })
        );
P
Peter Pan 已提交
35 36
    } else if (isDemo) {
        const {default: demo} = await import('@visualdl/demo');
37
        app.use(apiUrl, demo);
P
Peter Pan 已提交
38
    } else if (isDev) {
39 40
        const {middleware: mock} = await import('@visualdl/mock');
        app.use(apiUrl, mock({delay: delay ? () => Math.random() * delay : 0}));
41 42
    } else {
        console.warn('Server is running in production mode but no backend address specified.');
43 44
    }

45
    if (publicPath !== '/') {
46
        app.get('/', (_req, res) => {
47 48 49 50
            res.redirect(publicPath);
        });
    }

51 52
    if (pingUrl && pingUrl !== '/' && pingUrl !== publicPath && pingUrl.startsWith('/')) {
        app.get(pingUrl, (_req, res) => {
P
Peter Pan 已提交
53 54 55 56 57
            res.type('text/plain');
            res.status(200).send('OK!');
        });
    }

58
    app.use(publicPath, express.static(root, {index: false}));
59

60
    app.get(/\.wasm/, (_req, res, next) => {
61 62 63 64
        res.type('application/wasm');
        next();
    });

65 66 67
    app.get('*', (_req, res) => {
        res.sendFile('index.html', {root});
    });
68

69
    const server = app.listen(port, host, () => {
70 71 72
        process.send?.('ready');
        console.log(`> Ready on http://${host}:${port}`);
        process.on('SIGINT', () => {
73
            server.close(err => {
74 75 76 77 78 79 80
                if (err) {
                    throw err;
                }
                process.exit(0);
            });
        });
    });
81 82 83 84 85 86 87
}

if (require.main === module) {
    start();
}

export default start;
88

89
export {app};