add db class

This commit is contained in:
2025-11-07 16:29:26 +01:00
parent a81cb671b8
commit 43824ce284
10 changed files with 153 additions and 42 deletions

85
src/server/db.ts Normal file
View File

@@ -0,0 +1,85 @@
import { Database } from 'bun:sqlite';
// create tables if they don't exist
const createTableScript = `
-- GROUP TRABLE --
CREATE TABLE IF NOT EXISTS group (
id INTEGER PRIMARY KEY AUTOINCREMENT,
code TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
mail TEXT NOT NULL,
image BLOB,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
-- USER TABLE --
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
mail TEXT NOT NULL,
image BLOB,
);
-- GROUP_MEMBER TABLE --
CREATE TABLE IF NOT EXISTS group_member (
id INTEGER PRIMARY KEY AUTOINCREMENT,
group_id INTEGER,
user_id INTEGER,
UNIQUE(email, group_id),
FOREIGN KEY(group_id) REFERENCES groups(id),
FOREIGN KEY(user_id) REFERENCES users(id)
);
-- BAN TABLE --
CREATE TABLE IF NOT EXISTS ban (
id INTEGER PRIMARY KEY AUTOINCREMENT,
group_id INTEGER,
user_id INTEGER,
user_id2 INTEGER,
FOREIGN KEY(group_id) REFERENCES groups(id),
FOREIGN KEY(user_id) REFERENCES users(id),
FOREIGN KEY(user_id2) REFERENCES users(id)
UNIQUE(group_id, user_id, user_id2),
);
-- WHISHLIST TABLE --
CREATE TABLE IF NOT EXISTS wishlist (
id INTEGER PRIMARY KEY AUTOINCREMENT,
group_id INTEGER,
user_id INTEGER,
item TEXT NOT NULL,
FOREIGN KEY(group_id) REFERENCES groups(id),
FOREIGN KEY(user_id) REFERENCES users(id)
);
`;
class DB {
private instance: Database = new Database();
private prepareDB () {
this.instance.run(createTableScript);
}
public async getGroup(id: string) {
const stmt = this.instance.prepare('SELECT * FROM groups WHERE code = ?');
const group = await stmt.get(id);
return group;
}
public createGroup(code: string): { id: number | bigint} {
const stmt = this.instance.prepare('INSERT INTO groups (code) VALUES (?)');
const changes = stmt.run(code);
console.log('Inserted group with ID:', changes);
return { id: changes.lastInsertRowid };
};
constructor(url: string = './data.sqlite') {
if (this.instance) {
this.instance = new Database(url);
this.prepareDB();
console.log('Database initialized at', url);
}
}
}
export default DB;