Files
citpl_cms_react_express_pos…/server/db.js
T

100 lines
2.8 KiB
JavaScript

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import bcrypt from 'bcryptjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
const CONTENT_FILE = path.join(DATA_DIR, 'content.json');
const ADMIN_FILE = path.join(DATA_DIR, 'admin.json');
const SEED_FILE = path.join(__dirname, 'seed', 'default-content.json');
function ensureDataDir() {
if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR, { recursive: true });
}
}
function readJson(filePath, fallback = null) {
if (!fs.existsSync(filePath)) return fallback;
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
}
function writeJson(filePath, data) {
ensureDataDir();
fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
}
export function initDb() {
ensureDataDir();
if (!fs.existsSync(CONTENT_FILE)) {
const seed = readJson(SEED_FILE);
writeJson(CONTENT_FILE, { ...seed, updatedAt: new Date().toISOString() });
console.log('Seeded content database from default-content.json');
}
// Keep login credentials in sync with .env (ADMIN_USERNAME / ADMIN_PASSWORD)
const username = process.env.ADMIN_USERNAME || 'admin';
const password = process.env.ADMIN_PASSWORD || 'admin123';
if (process.env.ADMIN_USERNAME || process.env.ADMIN_PASSWORD || !fs.existsSync(ADMIN_FILE)) {
writeJson(ADMIN_FILE, {
username,
passwordHash: bcrypt.hashSync(password, 12),
});
console.log(`Admin credentials loaded from .env (username: ${username})`);
}
}
export function getContent() {
const data = readJson(CONTENT_FILE, {});
const { updatedAt, ...content } = data;
return { content, updatedAt };
}
export function getFullContentRecord() {
return readJson(CONTENT_FILE, {});
}
export function updateSection(section, sectionData) {
const record = getFullContentRecord();
record[section] = sectionData;
record.updatedAt = new Date().toISOString();
writeJson(CONTENT_FILE, record);
return record.updatedAt;
}
export function updateAllContent(content) {
const record = { ...content, updatedAt: new Date().toISOString() };
writeJson(CONTENT_FILE, record);
return record.updatedAt;
}
export function getAdmin() {
return readJson(ADMIN_FILE);
}
export function updateAdminPassword(passwordHash) {
const admin = getAdmin();
admin.passwordHash = passwordHash;
writeJson(ADMIN_FILE, admin);
}
const LEADS_FILE = path.join(DATA_DIR, 'contact-leads.json');
export function saveLead(leadData) {
const leads = readJson(LEADS_FILE, []);
const newLead = {
id: `lead_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
...leadData,
createdAt: new Date().toISOString()
};
leads.unshift(newLead);
writeJson(LEADS_FILE, leads);
return newLead;
}
export function getLeads() {
return readJson(LEADS_FILE, []);
}