72 lines
1.9 KiB
TypeScript
72 lines
1.9 KiB
TypeScript
import Database from 'better-sqlite3'
|
|
import { join } from 'path'
|
|
import { existsSync, mkdirSync } from 'fs'
|
|
import { dirname } from 'path'
|
|
|
|
let db: Database.Database
|
|
|
|
export async function getDatabase() {
|
|
if (!db) {
|
|
// Use absolute path in production (Docker), relative path in development
|
|
const isProduction = process.env.NODE_ENV === 'production'
|
|
const dbPath = isProduction
|
|
? '/app/data/sermons.db'
|
|
: './data/sermons.db'
|
|
|
|
// Ensure directory exists
|
|
const dir = dirname(dbPath)
|
|
if (!existsSync(dir)) {
|
|
mkdirSync(dir, { recursive: true })
|
|
}
|
|
|
|
db = new Database(dbPath)
|
|
await initializeDatabase(db)
|
|
}
|
|
return db
|
|
}
|
|
|
|
async function initializeDatabase(db: Database.Database) {
|
|
// Create sermons table
|
|
db.exec(`
|
|
CREATE TABLE IF NOT EXISTS sermons (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
title TEXT NOT NULL,
|
|
date TEXT NOT NULL,
|
|
slug TEXT UNIQUE NOT NULL,
|
|
bible_references TEXT,
|
|
personal_application TEXT,
|
|
pastor_challenge TEXT,
|
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
)
|
|
`)
|
|
|
|
// Create users table for authentication
|
|
db.exec(`
|
|
CREATE TABLE IF NOT EXISTS users (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
username TEXT UNIQUE NOT NULL,
|
|
password_hash TEXT NOT NULL,
|
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
)
|
|
`)
|
|
|
|
// Create default admin user if it doesn't exist
|
|
const config = useRuntimeConfig()
|
|
const bcrypt = await import('bcryptjs')
|
|
const saltRounds = 10
|
|
const passwordHash = await bcrypt.hash(config.adminPassword, saltRounds)
|
|
|
|
const existingAdmin = db.prepare('SELECT id FROM users WHERE username = ?').get('admin')
|
|
if (!existingAdmin) {
|
|
db.prepare('INSERT INTO users (username, password_hash) VALUES (?, ?)').run('admin', passwordHash)
|
|
}
|
|
}
|
|
|
|
export function closeDatabase() {
|
|
if (db) {
|
|
db.close()
|
|
db = null
|
|
}
|
|
}
|