initial commit
This commit is contained in:
62
database.ts
Normal file
62
database.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user