All checks were successful
Build and Push Container / build (push) Successful in 1m7s
47 lines
1.2 KiB
TypeScript
47 lines
1.2 KiB
TypeScript
import { readFile, writeFile } from 'node:fs/promises';
|
|
import { readFileSync, writeFileSync } from 'node:fs';
|
|
|
|
export class lazyKv {
|
|
path: string;
|
|
|
|
constructor(_path: string) {
|
|
this.path = _path;
|
|
this.init();
|
|
}
|
|
|
|
init(): void {
|
|
try {
|
|
readFileSync(this.path, 'utf-8');
|
|
} catch {
|
|
writeFileSync(this.path, '{}', 'utf-8');
|
|
} finally {
|
|
console.log(`LazyKv: initialized ${this.path}`);
|
|
}
|
|
}
|
|
|
|
async get<T>(key: string, fallback?: T): Promise<T> {
|
|
const data = await readFile(this.path, 'utf-8');
|
|
const json = JSON.parse(data) as Record<string, T>;
|
|
|
|
return json[key] ?? (fallback || null);
|
|
}
|
|
|
|
async set<T>(key: string, value: T): Promise<void> {
|
|
const data = await readFile(this.path, 'utf-8');
|
|
const json = JSON.parse(data) as Record<string, T>;
|
|
|
|
json[key] = value;
|
|
|
|
await writeFile(this.path, JSON.stringify(json, null, 2), 'utf-8');
|
|
}
|
|
|
|
async delete(key: string): Promise<void> {
|
|
const data = await readFile(this.path, 'utf-8');
|
|
const json = JSON.parse(data) as Record<string, unknown>;
|
|
|
|
delete json[key];
|
|
|
|
await writeFile(this.path, JSON.stringify(json, null, 2), 'utf-8');
|
|
}
|
|
}
|