storage.ts•2.21 kB
import fs from "fs";
import path from "path";
const dataPath = path.join(process.cwd(), "data", "state.json");
export type DbConfig = {
name: string;
kind: "postgres" | "mysql";
host: string;
port: number;
user: string;
password: string;
database: string;
// Back-compat: `ssl` is boolean; `sslMode` is preferred.
ssl?: boolean;
sslMode?: "disable" | "require" | "no-verify";
};
export type HistoryEntry = {
dbName: string;
tables: string[];
lastUsed: string; // ISO string
};
type State = {
configs: DbConfig[];
history: HistoryEntry[];
};
const defaultState: State = { configs: [], history: [] };
function ensureStore() {
if (!fs.existsSync(dataPath)) {
fs.mkdirSync(path.dirname(dataPath), { recursive: true });
fs.writeFileSync(dataPath, JSON.stringify(defaultState, null, 2));
}
}
function readState(): State {
ensureStore();
const raw = fs.readFileSync(dataPath, "utf8");
try {
return JSON.parse(raw) as State;
} catch (err) {
console.error("state.json was invalid; resetting", err);
fs.writeFileSync(dataPath, JSON.stringify(defaultState, null, 2));
return defaultState;
}
}
function writeState(state: State) {
ensureStore();
fs.writeFileSync(dataPath, JSON.stringify(state, null, 2));
}
export function listConfigs(): DbConfig[] {
return readState().configs;
}
export function saveConfig(config: DbConfig) {
const state = readState();
const idx = state.configs.findIndex((c) => c.name === config.name);
if (idx >= 0) {
state.configs[idx] = config;
} else {
state.configs.push(config);
}
writeState(state);
}
export function getConfig(name: string): DbConfig | undefined {
return readState().configs.find((c) => c.name === name);
}
export function recordHistory(entry: HistoryEntry) {
const state = readState();
const existingIdx = state.history.findIndex((h) => h.dbName === entry.dbName);
if (existingIdx >= 0) {
state.history[existingIdx] = entry;
} else {
state.history.push(entry);
}
writeState(state);
}
export function listHistory(): HistoryEntry[] {
return readState().history.sort(
(a, b) => new Date(b.lastUsed).getTime() - new Date(a.lastUsed).getTime(),
);
}