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
82 lines (69 loc) · 2 KB
/
Copy pathfileStore.ts
File metadata and controls
82 lines (69 loc) · 2 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
/** @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 {
try {
if (!fs.existsSync(this.filePath)) {
fs.writeFileSync(this.filePath, JSON.stringify([], null, 2), 'utf-8');
}
} catch {
// fs is unavailable or read-only (browser, edge runtime, serverless FS).
// Failure logging degrades to a no-op instead of crashing construction.
}
}
async save(request: FailedRequest): Promise<void> {
try {
const logs = await this.loadAll();
logs.push(request);
fs.writeFileSync(this.filePath, JSON.stringify(logs, null, 2), 'utf-8');
} catch {
// best-effort logging; ignore write failures
}
}
async loadAll(): Promise<FailedRequest[]> {
try {
const content = fs.readFileSync(this.filePath, 'utf-8');
return JSON.parse(content);
} catch {
return [];
}
}
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> {
try {
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;
} catch {
return false;
}
}
async clear(): Promise<void> {
try {
fs.writeFileSync(this.filePath, JSON.stringify([], null, 2), 'utf-8');
} catch {
// best-effort logging; ignore write failures
}
}
async count(): Promise<number> {
const logs = await this.loadAll();
return logs.length;
}
getFilePath(): string {
return this.filePath;
}
}