Files
peworkshop/lib/db.js
T
2025-03-11 20:16:14 +00:00

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('./sqlite.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 };