forked from AubaidFarrukh/smart-retry
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfileStore.ts
More file actions
61 lines (48 loc) · 1.53 KB
/
Copy pathfileStore.ts
File metadata and controls
61 lines (48 loc) · 1.53 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
/** @format */
import fs from 'fs';
import path from 'path';
import { FailedRequest } from './types';
export class FileStore {
private filePath: string;
constructor(filePath?: string) {
this.filePath = filePath || path.join(process.cwd(), 'smart-retry-log.json');
this.ensureFileExists();
}
private ensureFileExists(): void {
if (!fs.existsSync(this.filePath)) {
fs.writeFileSync(this.filePath, JSON.stringify([], null, 2), 'utf-8');
}
}
async save(request: FailedRequest): Promise<void> {
const logs = await this.loadAll();
logs.push(request);
fs.writeFileSync(this.filePath, JSON.stringify(logs, null, 2), 'utf-8');
}
async loadAll(): Promise<FailedRequest[]> {
const content = fs.readFileSync(this.filePath, 'utf-8');
return JSON.parse(content);
}
async findById(id: string): Promise<FailedRequest | undefined> {
const logs = await this.loadAll();
return logs.find((log) => log.id === id);
}
async remove(id: string): Promise<boolean> {
const logs = await this.loadAll();
const filtered = logs.filter((log) => log.id !== id);
if (filtered.length === logs.length) {
return false;
}
fs.writeFileSync(this.filePath, JSON.stringify(filtered, null, 2), 'utf-8');
return true;
}
async clear(): Promise<void> {
fs.writeFileSync(this.filePath, JSON.stringify([], null, 2), 'utf-8');
}
async count(): Promise<number> {
const logs = await this.loadAll();
return logs.length;
}
getFilePath(): string {
return this.filePath;
}
}