photosite/dist/db/index.js

119 lines
3.5 KiB
JavaScript
Raw Normal View History

2024-12-03 04:09:32 +00:00
"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() {
this.log = (0, log_1.createLog)('db');
this.db = new sqlite3_1.Database((0, env_1.envString)('DB', 'data/site.db'));
2024-12-09 20:15:27 +00:00
//this.db.run( 'PRAGMA journal_mode = WAL;');
2024-12-03 04:09:32 +00:00
}
async run(query, args = null) {
return new Promise((resolve, reject) => {
return this.db.run(query, args, (err, rows) => {
if (err)
return reject(err);
return resolve(true);
});
});
}
2024-12-09 20:15:27 +00:00
async all(query, args = null) {
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);
2024-12-09 20:15:27 +00:00
this.log.info(`Inserted new photo ${photo.name}`);
}
catch (err) {
throw err;
}
}
2024-12-09 20:15:27 +00:00
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 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;
}
2024-12-03 04:09:32 +00:00
}
exports.DB = DB;
module.exports = { DB };
//# sourceMappingURL=index.js.map