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

3 4
import express from 'express';
import middleware from './middleware';
5

6 7 8
const host = process.env.HOST || 'localhost';
const port = Number.parseInt(process.env.PORT || '', 10) || 8998;
const apiUrl = process.env.API_URL || '/api';
9

10 11 12 13 14
export interface Options {
    host?: string;
    port?: number;
    apiUrl?: string;
}
15

16
const server = express();
17

18 19
async function start(options?: Options) {
    const config = Object.assign({host, port, apiUrl}, options);
20

21
    server.use(config.apiUrl, middleware());
22

23 24 25 26 27 28 29 30 31 32 33 34 35
    const s = server.listen(config.port, config.host, () => {
        process.send?.('ready');
        console.log(`> Ready on http://${config.host}:${config.port}${config.apiUrl}`);
        process.on('SIGINT', () => {
            s.close((err: Error | undefined) => {
                if (err) {
                    throw err;
                }
                process.exit(0);
            });
        });
    });
}
P
Peter Pan 已提交
36

37 38 39
if (require.main === module) {
    start();
}
40

41
export {start, middleware};