first commit

This commit is contained in:
khuongnguyen committed 2026-11-28 20:37:00 +07:00
commit 41d9e9e8eb
21 files changed
+3538

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
import fs from "node:fs";
import path from "node:path";
import { VPS, vpsListSchema } from "../types/vps.js";
export class VPSRepository {
private filePath: string;
private cache: VPS[] | null = null;
constructor(filePath?: string) {
this.filePath = filePath || process.env.VPS_DATA_PATH || path.resolve(process.cwd(), "data/vps.json");
}
/**
* Loads and validates VPS records from the JSON data file.
*/
public load(): VPS[] {
const resolvedPath = path.resolve(this.filePath);
if (!fs.existsSync(resolvedPath)) {
throw new Error(`Inventory data file not found at path: ${resolvedPath}`);
}
let rawData: string;
try {
rawData = fs.readFileSync(resolvedPath, "utf-8");
} catch (err) {
throw new Error(`Failed to read inventory data file: ${(err as Error).message}`);
}
let parsed: unknown;
try {
parsed = JSON.parse(rawData);
} catch (err) {
throw new Error(`Corrupted JSON inventory data file: ${(err as Error).message}`);
}
const validation = vpsListSchema.safeParse(parsed);
if (!validation.success) {
const issueDetails = validation.error.issues
.map((issue) => `[${issue.path.join(".")}]: ${issue.message}`)
.join("; ");
throw new Error(`Invalid VPS inventory data structure: ${issueDetails}`);
}
this.cache = validation.data;
return this.cache;
}
/**
* Returns all VPS records.
*/
public getAll(): VPS[] {
if (!this.cache) {
return this.load();
}
return this.cache;
}
/**
* Finds a VPS by exact ID.
*/
public getById(id: string): VPS | undefined {
return this.getAll().find((vps) => vps.id === id);
}
/**
* Finds a VPS by name (case-insensitive).
*/
public getByName(name: string): VPS | undefined {
const trimmed = name.trim().toLowerCase();
return this.getAll().find((vps) => vps.name.toLowerCase() === trimmed);
}
/**
* Force reloads the data from disk.
*/
public reload(): VPS[] {
this.cache = null;
return this.load();
}
}