This repository has been archived by the owner on Jan 18, 2023. It is now read-only.
/
dev.ts
102 lines (88 loc) · 2.5 KB
/
dev.ts
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
100
101
102
import { CommandBuilder } from 'yargs'; // eslint-disable-line
import { join, relative } from 'path';
import emojic from 'emojic';
import chalk from 'chalk';
import decache from 'decache';
import logger from '../../utils/logger';
import Route from '../../types/route';
import { server } from '../../index';
import findRoutes from '../../utils/find-routes';
import addRoute from '../../utils/add-route';
import importRoutes from '../../utils/import-routes';
export const command = 'dev [dir]';
export const aliases: string[] = ['d'];
export const desc = 'start a development server';
export const builder: CommandBuilder = {
log: {
alias: 'l',
description: 'enable or disable logs',
boolean: true,
default: true,
},
port: {
alias: 'p',
description: 'specify which port the server should run on',
},
dir: {
default: './',
description: 'base directory for the light server',
hidden: true,
},
};
interface Args {
log: boolean;
dir: string;
port?: string;
}
const handle = async (argv: Args): Promise<void> => {
logger.start(`${emojic.fire} igniting the server ${emojic.fire}`);
const cwd = join(process.cwd(), argv.dir);
const routesPath = join(cwd, './routes');
const opts = {
isDev: true,
};
const app = server({
routes: routesPath,
opts,
});
interface ProcessEnv {
[key: string]: string | number | undefined;
}
const {
HOST = '0.0.0.0',
}: ProcessEnv = process.env;
let {
PORT = 3000,
}: ProcessEnv = process.env;
if (argv.port) {
PORT = argv.port;
}
app.server.listen(PORT, (HOST as any), (): void => {
logger.listening(`on port ${PORT}`);
logger.hmr('starting the hot reloader');
const chokidar = require('chokidar'); // eslint-disable-line
const watcher = chokidar.watch(cwd);
watcher.on('ready', (): void => {
logger.hmr('watching for changes');
});
watcher.on('change', (p: string): void => {
logger.hmr(`swapping out ${chalk.yellow(relative(cwd, p))}`);
app.router.reset();
decache(join(routesPath, '../', 'routes.js'));
const files: any[] = findRoutes(routesPath);
files.forEach((f): void => {
decache(f.handler);
});
const routeObjs = importRoutes(files, routesPath, true);
routeObjs.forEach((route: Route): void => {
addRoute(app.router, route, opts);
});
});
});
};
export const handler = (argv: Args): void => {
handle(argv).catch((err: Error): void => {
logger.fatal(err);
process.exit(1);
});
};