fix: config file not reloaded on change

Massimo Melina committed Jan 20, 2022 at 17:16 UTC 6de859eff7bb70e561fc113a6ea708c32b48103f
1 file changed +15 -15
src/watchLoad.ts
+15 -15
@@ -9,23 +9,25 @@ interface Options { failOnFirstAttempt?: ()=>void }
9
10 export function watchLoad(path:string, parser:(data:any)=>void|Promise<void>, { failOnFirstAttempt }:Options={}): WatchLoadCanceller {
11 let doing = false
12 - let first = true
12 let watcher: FSWatcher
13 const debounced = _.debounce(load, 500)
15 - debounced()
16 - const timer = setInterval(()=>{
14 + let initDone = false
15 + init()
16 + return () => {
17 + initDone = true // stop trying
18 + watcher?.close()
19 + }
20 +
21 + function init() {
22 try {
18 - watcher = watch(path, debounced)
23 debounced()
24 + watcher = watch(path, debounced)
25 + initDone = true
26 + }
27 + catch {
28 + if (initDone)
29 + setTimeout(init, 1000)
30 }
21 - catch {}
22 - }, 1000)
23 - let running = true
24 - return () => {
25 - if (!running) return
26 - running = false
27 - clearInterval(timer)
28 - watcher?.close()
31 }
32
33 async function load(){
@@ -38,14 +40,12 @@ export function watchLoad(path:string, parser:(data:any)=>void|Promise<void>, {
40 if (path.endsWith('.yaml'))
41 data = yaml.parse(data)
42 } catch (e) {
41 - if (first)
43 + if (initDone)
44 failOnFirstAttempt?.()
45 doing = false
46 console.debug('cannot read', path, String(e))
47 return
48 }
47 - first = false
48 - clearInterval(timer)
49 await parser(data)
50 doing = false
51 }