60 lines
1.8 KiB
TypeScript
60 lines
1.8 KiB
TypeScript
const STORAGE_KEY = 'isssteleon.connect.savedSqlConnections';
|
|
const MAX_SAVED = 20;
|
|
|
|
/**
|
|
* A database connection's shape, remembered across visits so the form
|
|
* doesn't need retyping. Never the password: credentials travel with every
|
|
* request and are never stored (see `sql-source.ts`), so reconnecting
|
|
* through a saved entry still asks for it.
|
|
*/
|
|
export interface SavedSqlConnection {
|
|
id: string;
|
|
label: string;
|
|
engine: string;
|
|
host: string;
|
|
port: number | null;
|
|
database: string;
|
|
user: string;
|
|
}
|
|
|
|
export type SavedSqlConnectionInput = Omit<SavedSqlConnection, 'id'>;
|
|
|
|
function connectionId(entry: SavedSqlConnectionInput): string {
|
|
return [entry.engine, entry.host, entry.port ?? '', entry.database, entry.user].join('|');
|
|
}
|
|
|
|
function readAll(): SavedSqlConnection[] {
|
|
try {
|
|
const raw = localStorage.getItem(STORAGE_KEY);
|
|
const parsed = raw ? JSON.parse(raw) : [];
|
|
return Array.isArray(parsed) ? parsed : [];
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
function writeAll(entries: SavedSqlConnection[]): void {
|
|
try {
|
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(entries));
|
|
} catch {
|
|
// Private browsing, a cleared/blocked store, or a full quota: the form
|
|
// just won't remember anything this time, nothing to surface to the user.
|
|
}
|
|
}
|
|
|
|
export function listSavedSqlConnections(): SavedSqlConnection[] {
|
|
return readAll();
|
|
}
|
|
|
|
/** Upserts by connection shape (engine/host/port/database/user), newest first. */
|
|
export function saveSqlConnection(entry: SavedSqlConnectionInput): SavedSqlConnection {
|
|
const saved: SavedSqlConnection = { ...entry, id: connectionId(entry) };
|
|
const rest = readAll().filter((existing) => existing.id !== saved.id);
|
|
writeAll([saved, ...rest].slice(0, MAX_SAVED));
|
|
return saved;
|
|
}
|
|
|
|
export function removeSqlConnection(id: string): void {
|
|
writeAll(readAll().filter((existing) => existing.id !== id));
|
|
}
|