"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DB = void 0; require("dotenv/config"); const log_1 = require("../log"); const sqlite3_1 = require("sqlite3"); const env_1 = require("../env"); class DB { constructor() { const databaseFile = (0, env_1.envString)('DB', 'data/site.db'); this.log = (0, log_1.createLog)('db'); this.db = new sqlite3_1.Database(databaseFile); this.db.run('PRAGMA journal_mode = WAL;'); this.log.info(`DB: ${databaseFile}`); } async run(query, args = []) { return new Promise((resolve, reject) => { return this.db.run(query, args, (err, rows) => { if (err) return reject(err); return resolve(true); }); }); } async all(query, args = []) { return new Promise((resolve, reject) => { return this.db.all(query, args, (err, rows) => { if (err) return reject(err); return resolve(rows); }); }); } toBoolean(val) { return val === 1 ? true : false; } fromBoolean(val) { return val ? 1 : 0; } //CASE WHEN LOWER(active) = 'true' THEN 1 ELSE 0 END AS active_bool async create(photo) { const keys = Object.keys(photo); const query = `INSERT INTO photos (${keys.join(',')}) VALUES (${keys.map(el => '?').join(',')});`; const values = []; for (let key of keys) { if (typeof photo[key] === 'boolean') { values.push(this.fromBoolean(photo[key])); } else { values.push(photo[key]); } } try { await this.run(query, values); this.log.info(`Inserted new photo ${photo.name}`); } catch (err) { throw err; } } async existsName(name) { const query = `SELECT id FROM photos WHERE name = ? LIMIT 1;`; let rows = []; let exists = false; try { rows = await this.all(query, [name]); } catch (err) { this.log.error(`Error finding photo by name ${name}`, err); } if (rows.length > 0) { exists = true; } return exists; } async existsHash(hash) { const query = `SELECT id FROM photos WHERE hash = ? LIMIT 1;`; let rows = []; let exists = false; try { rows = await this.all(query, [hash]); } catch (err) { this.log.error(`Error finding photo by hash ${hash}`, err); } if (rows.length > 0) { exists = true; } return exists; } async getAll() { const query = `SELECT * FROM photos ORDER BY score ASC, created DESC;`; let rows = []; try { rows = await this.all(query); } catch (err) { this.log.error(`Error getting all photos`, err); } return rows; } async cacheLocation(location, latlng) { const query = `INSERT OR IGNORE INTO geocode (location, latitude, longitude) VALUES (?, ?, ?);`; try { await this.run(query, [location, latlng.latitude, latlng.longitude]); } catch (err) { //ignore } } async getLocation(location) { const query = `SELECT latitude, longitude FROM geocode WHERE location = ? LIMIT 1;`; let rows = []; let res = null; try { rows = await this.all(query, [location]); } catch (err) { //ignore } if (rows.length > 0) { res = { latitude: rows[0].latitude, longitude: rows[0].longitude }; } return res; } } exports.DB = DB; module.exports = { DB }; //# sourceMappingURL=index.js.map