generated from acttoreact/ts-node-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
105 lines (93 loc) · 2.35 KB
/
index.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
103
104
105
import path from 'path';
import chokidar from 'chokidar';
import { ensureDir } from '@a2r/fs';
import { targetPath, proxyPath, proxies } from './settings';
import initWatchers from './utils/initWatchers';
import { isJest } from './tools/isJest';
/**
* API Watcher process
*/
interface Process {
type: 'start' | 'stop';
callback: (watchers: chokidar.FSWatcher[]) => void;
}
const pendingProcesses: Process[] = [];
const serverPath = path.resolve(__dirname, targetPath);
const proxyDestPath = path.resolve(__dirname, proxyPath);
let runningProcess: 'start' | 'stop' = null;
/**
* Current active watchers
*/
export const activeWatchers: chokidar.FSWatcher[] = [];
/**
* Executes pending processes
*/
const executeProcess = async (): Promise<void> => {
if (!runningProcess) {
const pendingProcess = pendingProcesses.shift();
if (pendingProcess) {
const { type, callback } = pendingProcess;
runningProcess = type;
if (activeWatchers.length) {
await Promise.all(
activeWatchers.map(async (watcher) => {
await watcher.close();
}),
);
activeWatchers.splice(0, activeWatchers.length);
}
if (type === 'start') {
const watchers = await initWatchers(serverPath, __dirname);
activeWatchers.push(...watchers);
}
callback(activeWatchers);
runningProcess = null;
executeProcess();
}
}
};
/**
* Adds a new process to queue
*/
const addProcessToQueue = (
type: 'start' | 'stop',
callback?: (watchers: chokidar.FSWatcher[]) => void,
): void => {
pendingProcesses.push({ type, callback });
executeProcess();
};
/**
* Stops watchers
*/
export const stop = (): Promise<void> =>
new Promise((resolve) => {
addProcessToQueue('stop', () => {
resolve();
});
});
/**
* Starts watchers
*/
export const start = async (): Promise<chokidar.FSWatcher[]> =>
new Promise((resolve) => {
addProcessToQueue('start', (watchers) => {
resolve(watchers);
});
});
/**
* Restarts watchers
*/
export const restart = start;
/**
* Inits watchers by ensuring destination path and running start process
*/
const init = async (): Promise<void> => {
await ensureDir(proxyDestPath);
await Promise.all(
proxies.map((proxy) => ensureDir(path.resolve(proxyDestPath, proxy))),
);
await start();
};
if (!isJest()) {
init();
}