/
FSPersister.ts
67 lines (57 loc) · 1.83 KB
/
FSPersister.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { IPersister } from '../IPersister';
import { IPathResolver } from './IPathResolver';
import { IFileSystemAdapter } from './IFileSystemAdapter';
/**
* Persists data using the node fs / path api
*/
export class FSPersister<T> implements IPersister<T> {
private get dir(): string {
return this.pathResolver.resolve(this.localFilesDirectory);
}
private get file(): string {
return this.pathResolver.resolve(this.localFilesDirectory, this.filePath);
}
constructor(
private localFilesDirectory: string,
private filePath: string,
private key: string,
private pathResolver: IPathResolver,
private fileSystemAdapter: IFileSystemAdapter
) {
this.ensureLocalFilesDirExists();
this.ensureFileExists();
}
public Retrieve(): any[] {
const json = this.retrieveDataFileJson();
return json[this.key] ? json[this.key] : [];
}
public Persist(items: any[]): void {
const json = this.retrieveDataFileJson();
json[this.key] = items;
this.fileSystemAdapter.writeFileSync(this.file, JSON.stringify(json));
}
public Purge(): void {
this.Persist([]);
}
private ensureLocalFilesDirExists() {
if (!this.fileSystemAdapter.existsSync(this.dir)) {
this.fileSystemAdapter.mkdirSync(this.dir);
}
}
private ensureFileExists() {
try {
this.fileSystemAdapter.accessSync(this.file, this.fileSystemAdapter.constants.W_OK);
} catch (error) {
this.writeBlankJsonToFile();
}
}
private writeBlankJsonToFile() {
const blankJson = {};
this.fileSystemAdapter.writeFileSync(this.file, JSON.stringify(blankJson));
}
private retrieveDataFileJson(): any {
const fileContents = this.fileSystemAdapter.readFileSync(
this.pathResolver.resolve(this.localFilesDirectory, this.filePath), 'utf8');
return JSON.parse(fileContents.toString());
}
}