mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-07 19:50:20 +00:00
69 lines
1.8 KiB
JavaScript
69 lines
1.8 KiB
JavaScript
// lib/db.js
|
|
let sqlite3;
|
|
|
|
// Only import sqlite3 on server-side
|
|
if (typeof window === 'undefined') {
|
|
sqlite3 = require('sqlite3').verbose();
|
|
}
|
|
|
|
// Initialize the database connection
|
|
function getDb() {
|
|
if (!sqlite3) {
|
|
console.error('Cannot access SQLite on the client side');
|
|
return null;
|
|
}
|
|
|
|
return new sqlite3.Database('./clue_hunt.db', (err) => {
|
|
if (err) {
|
|
console.error('Error opening database:', err.message);
|
|
} else {
|
|
console.log('Connected to the SQLite database.');
|
|
}
|
|
});
|
|
}
|
|
|
|
// Helper function to run queries with results
|
|
async function query(sql, params = []) {
|
|
if (typeof window !== 'undefined') {
|
|
throw new Error('Database queries cannot be executed on the client side');
|
|
}
|
|
|
|
const db = getDb();
|
|
return new Promise((resolve, reject) => {
|
|
db.all(sql, params, (err, rows) => {
|
|
if (err) {
|
|
reject(err);
|
|
} else {
|
|
resolve(rows);
|
|
}
|
|
db.close(); // Close the database connection
|
|
});
|
|
});
|
|
}
|
|
|
|
// Helper for single row queries
|
|
async function queryOne(sql, params = []) {
|
|
const rows = await query(sql, params);
|
|
return rows && rows.length > 0 ? rows[0] : null;
|
|
}
|
|
|
|
// Helper for insert/update/delete operations
|
|
async function run(sql, params = []) {
|
|
if (typeof window !== 'undefined') {
|
|
throw new Error('Database operations cannot be executed on the client side');
|
|
}
|
|
|
|
const db = getDb();
|
|
return new Promise((resolve, reject) => {
|
|
db.run(sql, params, function(err) {
|
|
if (err) {
|
|
reject(err);
|
|
} else {
|
|
resolve({ lastID: this.lastID, changes: this.changes });
|
|
}
|
|
db.close(); // Close the database connection
|
|
});
|
|
});
|
|
}
|
|
|
|
module.exports = { query, queryOne, run }; |