fix: double loading of accounts file at start
Massimo Melina committed
Mar 30, 2022 at 16:29 UTC
a2e3ec8858240fba4dad2b321226bcb98c3b1dd5
1 file changed
+12
-11
server/src/watchLoad.ts
+12
-11
@@ -17,9 +17,8 @@ export function watchLoad(path:string, parser:(data:any)=>void|Promise<void>, {
17
const debounced = debounceAsync(load, 500, { leading: true })
18
let retry: NodeJS.Timeout
19
let saving: Promise<unknown> | undefined
20
- init()
21
- if (!watcher)
22
- failedOnFirstAttempt?.()
20
+ let lastStats: any
21
+ init().then(ok => ok || failedOnFirstAttempt?.())
22
return {
23
unwatch(){
24
watcher?.close()
@@ -33,19 +32,17 @@ export function watchLoad(path:string, parser:(data:any)=>void|Promise<void>, {
32
}
33
}
34
36
- function init() {
37
- let triggered = false
35
+ async function init() {
36
try {
37
+ debounced().then()
38
watcher = watch(path, ()=> {
40
- triggered = true
39
if (!saving)
40
debounced().then()
41
})
44
- if (!triggered)
45
- debounced().then() // if file is not accessible watch will throw, and we won't get here
42
+ return true // used actually just by the first invocation
43
}
47
- catch {
48
- retry = setTimeout(init, 1000) // manual watching until watch is successful
44
+ catch(e) {
45
+ retry = setTimeout(init, 3_000) // manual watching until watch is successful
46
}
47
}
48
@@ -54,7 +51,11 @@ export function watchLoad(path:string, parser:(data:any)=>void|Promise<void>, {
51
doing = true
52
let data: any
53
try {
57
- try {
54
+ try { // I've seen watch() firing 'change' without any change, so we'll check if any change is detectable before going on
55
+ const stats = await fs.stat(path)
56
+ if (stats.mtimeMs === lastStats?.mtimeMs) return
57
+ lastStats = stats
58
+
59
data = await readFileBusy(path)
60
console.debug('loaded', path)
61
}