-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileStore.ts
More file actions
88 lines (80 loc) · 2.21 KB
/
Copy pathFileStore.ts
File metadata and controls
88 lines (80 loc) · 2.21 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import fs from 'fs';
import path from 'path';
export default class FileStore {
historyPath: string;
/**
* node-cron-trigger store provider
* @param {string} historyPath
* @param {string} historyFileName
*/
constructor(historyPath: string, historyFileName: string = 'history.log') {
if (!historyPath) throw new Error('historyPath must be provided')
this.historyPath = path.join(historyPath, historyFileName);
this.#createHistoryLog();
}
/**
* save the tasks history
* @param {string} key
* @param {any} value
* @returns {Promise<boolean>}
*/
setItem(key: string, value: any): Promise<boolean> {
return new Promise((resolve, reject) => {
try {
const history = this.#getHistory();
history[key] = value;
this.#updateHistory(history);
resolve(true);
} catch (err) {
reject(err)
}
});
}
/**
* get the tasks history by key like 'history' key
* @param {string} key
* @returns {Promise<any>}
*/
getItem(key: string): Promise<any> {
return new Promise((resolve, reject) => {
try {
const data = this.#getHistory();
resolve(data[key]);
} catch (err) {
reject(err)
}
});
}
/**
* remove the tasks history by key like 'history' key
* @param {string} key
* @returns {Promise<boolean>}
*/
removeItem(key: string): Promise<boolean> {
return new Promise((resolve, reject) => {
try {
const history = this.#getHistory();
delete history[key];
this.#updateHistory(history);
resolve(true);
} catch (err) {
reject(err)
}
});
}
#getHistory() {
// handle when the file accidentally deleted
this.#createHistoryLog();
return JSON.parse(fs.readFileSync(this.historyPath, 'utf-8') || '{}');
}
#createHistoryLog(): void {
// check if the tasks history file exists in the current directory or not to create it
if (!fs.existsSync(this.historyPath)) {
fs.writeFileSync(this.historyPath, '{}');
}
}
// saving the tasks next run date in history.log
#updateHistory(historyObject: any) {
fs.writeFileSync(this.historyPath, JSON.stringify(historyObject), 'utf8');
}
}