better code: single source of truth
Massimo Melina committed
Sep 12, 2023 at 11:26 UTC
be62d5f85b79163e786f2139ff5392cf742fa7e7
2 files changed
+8
-9
src/config.ts
+1
-2
@@ -180,8 +180,7 @@ const saveDebounced = debounceAsync(async () => {
180
if (await stat(bak).then(x => aWeekAgo > Number(x.mtime || x.ctime), () => true))
181
await copyFile(filePath, bak).catch(() => {}) // ignore errors
182
183
- const txt = yaml.stringify({ ...state, version: VERSION }, { lineWidth:1000 })
184
- save(filePath, txt)
183
+ await save(yaml.stringify({ ...state, version: VERSION }, { lineWidth:1000 }))
184
.catch(err => console.error('Failed at saving config file, please ensure it is writable.', String(err)))
185
})
186
export const saveConfigAsap = () => void(saveDebounced())
src/watchLoad.ts
+7
-7
@@ -8,8 +8,8 @@ export type WatchLoadCanceller = () => void
8
9
interface Options { failedOnFirstAttempt?: ()=>void, immediateFirst?: boolean }
10
11
-type WriteFile = typeof fs.writeFile
12
-interface WatchLoadReturn { unwatch:WatchLoadCanceller, save:WriteFile }
11
+type WriteFile = (data: string) => Promise<void>
12
+interface WatchLoadReturn { unwatch:WatchLoadCanceller, save: WriteFile }
13
export function watchLoad(path:string, parser:(data:any)=>void|Promise<void>, { failedOnFirstAttempt, immediateFirst }:Options={}): WatchLoadReturn {
14
let doing = false
15
let watcher: FSWatcher | undefined
@@ -20,11 +20,11 @@ export function watchLoad(path:string, parser:(data:any)=>void|Promise<void>, {
20
install(true)
21
return {
22
unwatch: uninstall,
23
- save(...args:Parameters<WriteFile>) {
24
- return Promise.resolve(saving).then(() => // wait in case another is ongoing
25
- saving = fs.writeFile(...args).finally(() => // save but also keep track of the current operation
26
- saving = undefined)) // clear
27
- }
23
+ save: (data: string) => Promise.resolve(saving).catch(() => {}).then(() => { // wait in case another is ongoing
24
+ console.debug('writing', path)
25
+ return saving = fs.writeFile(path, data, 'utf8').finally(() => // save but also keep track of the current operation
26
+ saving = undefined)
27
+ }) // clear
28
}
29
30
function install(first=false) {