/
ZHuk7174
/
express-sqlite-tutorial
Обзор
Документация
Войти
/
ZHuk7174
/
express-sqlite-tutorial
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
database.js
62 строки
2 KB
ZHuk7174
начало
13 дек 2025, 12:31
13 дек 2025, 12:31
b1f64bc
Код
Авторство
О чём код?
const sqlite3 = require('sqlite3').verbose(); const path = require('path'); const DB_PATH = path.join(__dirname, '..', 'database.sqlite'); // Create database connection const db = new sqlite3.Database(DB_PATH, (err) => { if (err) { console.error('Error opening database:', err.message); } else { console.log('Connected to SQLite database'); } }); // Initialize database tables const initDatabase = () => { return new Promise((resolve, reject) => { db.serialize(() => { // Admin users table db.run(`CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP )`); // Tasks table db.run(`CREATE TABLE IF NOT EXISTS messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, body TEXT NOT NULL, user_id INTEGER NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY(user_id) REFERENCES users (id) )`, (err) => { if (err) { console.error('Error creating tables:', err.message); reject(err); } else { console.log('Database tables initialized successfully'); // Insert default admin user const bcrypt = require('bcryptjs'); const hashedPassword = bcrypt.hashSync('admin123', 10); db.run(`INSERT OR IGNORE INTO users (username, password) VALUES (?, ?)`, ['admin', hashedPassword], (err) => { if (err) { console.error('Error creating default admin:', err.message); } else { console.log('Default admin user created (username: admin, password: admin123)'); } resolve(); }); } }); }); }); }; module.exports = { db, initDatabase };