add db class
This commit is contained in:
85
src/server/db.ts
Normal file
85
src/server/db.ts
Normal 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;
|
||||
Reference in New Issue
Block a user