/
mod.ts
45 lines (37 loc) · 1.27 KB
/
mod.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
import { Application, error, info, log } from './deps.ts';
import { wsMiddleware } from './wsMiddleware.ts';
import { staticMiddleware } from './staticMiddleware.ts';
import { Options } from './types.ts';
import { reloadAll, reloadMiddleware } from './reloadScript.ts';
export { Options, reloadAll };
let timer: number;
const INTERVAL = 250;
export async function server(options: Options) {
const { port, root, watcher = watch, debug = false } = options;
const app = new Application();
// Logger
app.use(async (ctx, next) => {
log(`${ctx.request.method} ${ctx.request.url}`);
await next();
});
app.addEventListener('error', (evt) => {
error(
evt.context?.request.url.href,
debug ? evt.error : evt.error.message,
);
});
app.use(reloadMiddleware);
app.use(wsMiddleware);
app.use(staticMiddleware(options));
info(`Server started listening on port ${port}`);
app.listen({ port });
watcher && watcher(root);
}
export async function watch(root: string) {
info(`Watch for file changes ${root}`);
const watcher = Deno.watchFs(root, { recursive: true });
for await (const event of watcher) {
clearTimeout(timer);
timer = setTimeout(reloadAll, INTERVAL);
}
}