initial commit

This commit is contained in:
Robin Chappatte
2024-05-21 16:10:08 +02:00
commit 5c36b2f7bc
4 changed files with 139 additions and 0 deletions

62
database.ts Normal file
View File

@@ -0,0 +1,62 @@
import { Entry, Table } from "./table.ts";
type Tables = Record<string, Table<Entry>>;
export class Database {
private constructor(private filePath: string, private tables: Tables) {}
static async load(
filePath: string,
ifEmpty: (database: Database) => Promise<void>,
): Promise<Database> {
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<Entry> {
const table = this.tables[name];
if (!table) {
throw new Error(`Table ${name} does not exist.`);
}
return table;
}
}