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

3
import config from '@visualdl/core/next.config';
4 5
import express from 'express';
import next from 'next';
6 7
import nextI18Next from '@visualdl/core/utils/i18n';
import nextI18NextMiddleware from '@visualdl/i18n/middleware';
8
import {setConfig} from 'next/config';
9 10 11 12 13

const isDev = process.env.NODE_ENV !== 'production';

setConfig(config);

14
const host = process.env.HOST || 'localhost';
15
const port = Number.parseInt(process.env.PORT || '', 10) || 8999;
16
const backend = process.env.BACKEND;
17
const delay = Number.parseInt(process.env.DELAY || '', 10);
P
Peter Pan 已提交
18

19
const server = express();
20 21 22
const app = next({dev: isDev, conf: config});
const handle = app.getRequestHandler();

23
async function start() {
24 25
    await app.prepare();

26
    if (backend) {
P
Peter Pan 已提交
27
        const {createProxyMiddleware} = await import('http-proxy-middleware');
28
        server.use(config.env.API_URL, createProxyMiddleware({target: backend, changeOrigin: true}));
P
Peter Pan 已提交
29
    } else if (isDev) {
30 31
        const {default: mock} = await import('@visualdl/mock');
        server.use(config.env.API_URL, mock({delay: delay ? () => Math.random() * delay : 0}));
32 33
    }

34 35
    await nextI18Next.initPromise;
    server.use(nextI18NextMiddleware(nextI18Next));
36

37 38 39 40 41
    server.get(/\.wasm/, (_req, res, next) => {
        res.type('application/wasm');
        next();
    });

42 43
    server.get('*', (req, res) => handle(req, res));

44 45 46 47
    const s = server.listen(port, host, () => {
        process.send?.('ready');
        console.log(`> Ready on http://${host}:${port}`);
        process.on('SIGINT', () => {
48
            s.close((err: Error | undefined) => {
49 50 51 52 53 54 55
                if (err) {
                    throw err;
                }
                process.exit(0);
            });
        });
    });
56 57 58 59 60 61 62
}

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

export default start;
63 64

export {server, app};