From 6fd7d4855f26aa7f217094f815fc7c2ec14bed4f Mon Sep 17 00:00:00 2001 From: Kristóf Marussy Date: Tue, 28 Dec 2021 13:06:11 +0100 Subject: refactor: Get rid of dependency injector --- .../main/src/services/ConfigPersistenceService.ts | 23 +++++++--------------- 1 file changed, 7 insertions(+), 16 deletions(-) (limited to 'packages/main/src/services') diff --git a/packages/main/src/services/ConfigPersistenceService.ts b/packages/main/src/services/ConfigPersistenceService.ts index 61123d9..34d0e3e 100644 --- a/packages/main/src/services/ConfigPersistenceService.ts +++ b/packages/main/src/services/ConfigPersistenceService.ts @@ -17,28 +17,25 @@ * * SPDX-License-Identifier: AGPL-3.0-only */ -import { FSWatcher, watch } from 'fs'; +import { watch } from 'fs'; import { readFile, stat, writeFile } from 'fs/promises'; import JSON5 from 'json5'; import { throttle } from 'lodash'; import { join } from 'path'; import type { ConfigSnapshotOut } from '../stores/Config'; +import type { Disposer } from '../utils'; export type ReadConfigResult = { found: true; data: unknown; } | { found: false; }; export class ConfigPersistenceService { - static inject = ['userDataDir', 'configFileName'] as const; - private readonly configFilePath: string; private timeLastWritten: Date | null = null; - private watcher: FSWatcher | null = null; - constructor( private readonly userDataDir: string, - private readonly configFileName: string, + private readonly configFileName: string = 'config.json5', ) { this.configFileName = configFileName; this.configFilePath = join(this.userDataDir, this.configFileName); @@ -69,11 +66,7 @@ export class ConfigPersistenceService { this.timeLastWritten = stats.mtime; } - watchConfig(callback: () => Promise, throttleMs: number): void { - if (this.watcher !== null) { - throw new Error('watchConfig was already called'); - } - + watchConfig(callback: () => Promise, throttleMs: number): Disposer { const configChanged = throttle(async () => { let mtime: Date; try { @@ -90,11 +83,11 @@ export class ConfigPersistenceService { } }, throttleMs); - this.watcher = watch(this.userDataDir, { + const watcher = watch(this.userDataDir, { persistent: false, }); - this.watcher.on('change', (eventType, filename) => { + watcher.on('change', (eventType, filename) => { if (eventType === 'change' && (filename === this.configFileName || filename === null)) { configChanged()?.catch((err) => { @@ -102,9 +95,7 @@ export class ConfigPersistenceService { }); } }); - } - dispose(): void { - this.watcher?.close(); + return () => watcher.close(); } } -- cgit v1.2.3-54-g00ecf