Files
ECS-FullStack/backend/db.js
2025-10-03 08:39:32 -04:00

39 lines
1.0 KiB
JavaScript

const fs = require('fs');
const path = require('path');
const CryptoJS = require('crypto-js');
const encryptionKey = process.env.ENCRYPTION_KEY;
const dbPath = path.join(__dirname, 'db.json');
const readDb = () => {
try {
const data = fs.readFileSync(dbPath, 'utf8');
if (data) {
const bytes = CryptoJS.AES.decrypt(data, encryptionKey);
const decryptedData = bytes.toString(CryptoJS.enc.Utf8);
if (decryptedData) {
return JSON.parse(decryptedData);
}
}
return {};
} catch (error) {
if (error.code === 'ENOENT') {
return {};
}
console.error('Error reading or decrypting db.json:', error);
return {};
}
};
const writeDb = (db) => {
try {
const data = JSON.stringify(db, null, 2);
const encryptedData = CryptoJS.AES.encrypt(data, encryptionKey).toString();
fs.writeFileSync(dbPath, encryptedData, 'utf8');
} catch (error) {
console.error('Error encrypting or writing to db.json:', error);
}
};
module.exports = { readDb, writeDb, dbPath };