import sqlite3 from 'sqlite3' import bcrypt from 'bcryptjs' import ErrorType from '../error/types.error.js' import serverConfig from '../configuration/server.config.js' sqlite3.verbose() const tableName = 'Config' class Config { constructor(options = {}) { this.id = options.id this.startingDateRaid = options.startingDateRaid } static find() { return new Promise((resolve, reject) => { const db = openDB() db.serialize(() => { db.all(`SELECT * FROM ${tableName}`, (err, configs) => { if (err) reject(new Error(ErrorType.TECHNICAL_UNKNOWN)) else { if (configs.length) { const config = createConfigFromDB(configs[0]) resolve(config); } else reject(new Error(ErrorType.TECHNICAL_UNKNOWN)) } }) closeDB(db) }) }) } async update() { return new Promise((resolve, reject) => { const db = openDB(); db.serialize(() => { db.run(`UPDATE ${tableName} SET startingDateRaid = ${this.startingDateRaid} WHERE id = ${this.id}`, err => { if (err) reject(new Error(ErrorType.TECHNICAL_UNKNOWN)) else resolve() }) }) closeDB(db) }) } toJson() { return { id: this.id, startingDateRaid: this.startingDateRaid } } } export default Config function openDB() { const env = process.env.NODE_ENV || 'development' return new sqlite3.Database(serverConfig.database[env].path, err => { if (err) throw new Error(err) }) } function closeDB(db) { db.close(err => { if (err) throw new Error(err) }) } function createConfigFromDB(dbUser) { return new Config({ id: dbUser.id, startingDateRaid: dbUser.startingDateRaid }) }