Add better-sqlite3 to Node backend
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
let db: Database.Database | null = null;
|
||||
|
||||
export function getDatabase(): Database.Database {
|
||||
if (!db) {
|
||||
db = openDatabase();
|
||||
}
|
||||
return db;
|
||||
}
|
||||
|
||||
function openDatabase() {
|
||||
const dbPath = path.join(__dirname, '../../data/database.db');
|
||||
|
||||
db = new Database(dbPath);
|
||||
db.pragma('journal_mode = WAL');
|
||||
|
||||
console.log(`Database connected at ${dbPath}`);
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
function closeDatabase() {
|
||||
if (db) {
|
||||
db.close();
|
||||
db = null;
|
||||
console.log('Database connection closed');
|
||||
}
|
||||
}
|
||||
|
||||
process.on('SIGINT', closeDatabase);
|
||||
process.on('SIGTERM', closeDatabase);
|
||||
@@ -1,4 +1,7 @@
|
||||
import express from 'express';
|
||||
import { getDatabase } from './db';
|
||||
|
||||
const db = getDatabase();
|
||||
|
||||
const app = express();
|
||||
const PORT = 3001;
|
||||
@@ -9,6 +12,14 @@ app.get('/api/hello', (req, res) => {
|
||||
res.json({ message: 'Hello World!' });
|
||||
});
|
||||
|
||||
app.get('/api/db', (req, res) => {
|
||||
const result = db.prepare('SELECT 1 + 2 AS test').get();
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Server is running on http://localhost:${PORT}`);
|
||||
});
|
||||
|
||||
process.on('SIGINT', () => process.exit(0));
|
||||
process.on('SIGTERM', () => process.exit(0));
|
||||
|
||||
Reference in New Issue
Block a user