Files
Parchment/server/db/db.js
metacryst 493f1c2e1f init
2025-11-13 15:30:11 -06:00

76 lines
2.0 KiB
JavaScript

import chalk from 'chalk'
import path from 'path';
import fs from 'fs/promises';
import { pathToFileURL } from 'url';
export default class Database {
#nodes;
#edges;
#labels = {}
constructor() {
this.getData()
}
async getData() {
const dbData = await fs.readFile(path.join(process.cwd(), 'db/db.json'), 'utf8');
let dbJson;
try {
dbJson = JSON.parse(dbData);
} catch {
dbJson = []
}
this.#nodes = dbJson["nodes"];
this.#edges = dbJson["edges"];
console.log(chalk.yellow("DB established."))
Object.preventExtensions(this);
}
// superKey = "nodes" || "edges"
async writeData(superKey, key, value) {
const dbData = await fs.readFile(path.join(process.cwd(), 'db/db.json'), 'utf8');
let dbJson;
try {
dbJson = JSON.parse(dbData);
} catch {
dbJson = []
}
dbJson[superKey][key] = value;
await fs.writeFile(path.join(process.cwd(), 'db/db.json'), JSON.stringify(dbJson, null, 2), 'utf8')
}
async getLabelModels() {
const labelHandlers = {};
const labelDir = path.join(process.cwd(), 'src/model/labels');
const files = await fs.readdir(labelDir);
for (const file of files) {
if (!file.endsWith('.js')) continue;
const label = path.basename(file, '.js');
const modulePath = path.join(labelDir, file);
const module = await import(pathToFileURL(modulePath).href);
labelHandlers[label] = module.default;
if (!this.#labels[label]) {
this.#labels[label] = [];
}
}
return labelHandlers
}
generateUserID() {
let id = this.#labels["User"].length + 1;
while (this.get.user(`user-${id}`)) {
id++;
}
return `user-${id}`; // O(1) most of the time
}
async getAll() {
return { nodes: this.#nodes }
}
}