refactor: Use fs-extra instead of fs to simplify file access

* refactor: use fs-extra instead of fs

* tests: manual mocks for fs-extra base + ensureDir

* refactor: mockFileSystem + mockFs and mockFsExtra

* add remove mock and some further test tweaks

* test: FileDataAccessor tests passing

* refactor: remove try-catch due to fs-extra handlin

* refactor: fs-extra in atomicFileDataAccessor

* refactor: AtomicFileDataAccessor fs-extra

* test: fix coverage

* refactor: use read/writeJson from fs-extra

* refactor: less duplicate mocking code

* refactor: re-use opendir mocking code
This commit is contained in:
Jasper Vaneessen
2022-04-12 11:02:30 +02:00
committed by GitHub
parent dd568869ca
commit fe39f97ee0
12 changed files with 139 additions and 86 deletions

View File

@@ -1,4 +1,4 @@
import { promises as fsPromises } from 'fs';
import { writeJson, readJson } from 'fs-extra';
import type { ResourceIdentifier } from '../../http/representation/ResourceIdentifier';
import { isSystemError } from '../../util/errors/SystemError';
import type { ReadWriteLocker } from '../../util/locking/ReadWriteLocker';
@@ -70,8 +70,7 @@ export class JsonFileStorage implements KeyValueStorage<string, unknown> {
return this.locker.withWriteLock(this.lockIdentifier, async(): Promise<T> => {
const json = await this.getJson();
const result = updateFn(json);
const updatedText = JSON.stringify(json, null, 2);
await fsPromises.writeFile(this.filePath, updatedText, 'utf8');
await writeJson(this.filePath, json, { encoding: 'utf8', spaces: 2 });
return result;
});
}
@@ -81,8 +80,7 @@ export class JsonFileStorage implements KeyValueStorage<string, unknown> {
*/
private async getJson(): Promise<NodeJS.Dict<unknown>> {
try {
const text = await fsPromises.readFile(this.filePath, 'utf8');
return JSON.parse(text);
return await readJson(this.filePath, 'utf8');
} catch (error: unknown) {
if (isSystemError(error) && error.code === 'ENOENT') {
return {};