import { Entry, Table } from "./table.ts"; type Tables = Record>; export class Database { private constructor(private filePath: string, private tables: Tables) {} static async load( filePath: string, ifEmpty: (database: Database) => Promise, ): Promise { const database = new Database(filePath, {}); try { const data = await Deno.readTextFile(filePath); const parsedData = JSON.parse(data); for (const tableName in parsedData) { const table = new Table(() => database.saveDatabase()); table.entries = parsedData[tableName].entries; table.autoIncrementId = parsedData[tableName].autoIncrementId; database.tables[tableName] = table; } } catch (_) { // File doesn't exists already await ifEmpty(database); } return database; } private async saveDatabase() { const dataToSave: { [name: string]: { entries: Entry[]; autoIncrementId: number }; } = {}; for (const tableName in this.tables) { dataToSave[tableName] = { entries: this.tables[tableName].entries, autoIncrementId: this.tables[tableName].autoIncrementId, }; } await Deno.writeTextFile( this.filePath, JSON.stringify(dataToSave), ); } async createTable(name: string) { if (this.tables[name]) { throw new Error(`Table ${name} already exists.`); } this.tables[name] = new Table(this.saveDatabase.bind(this)); await this.saveDatabase(); } getTable(name: string): Table { const table = this.tables[name]; if (!table) { throw new Error(`Table ${name} does not exist.`); } return table; } }