traintimesPWA/server/db/dbmanager.js
2020-08-20 15:08:07 +01:00

233 lines
5.4 KiB
JavaScript

const logger = require('log4js').getLogger('DBManager');
const db = require('./connect');
const fecha = require('fecha');
logger.level = process.env.LOGGER_LEVEL || 'debug';
// exports.create = (req, res) => {
function prepareData(_obj) {
const newObj = Object.assign({}, { 'tweet':JSON.stringify(_obj) });
newObj.ts = parseInt(_obj.timestamp_ms, 10);
newObj.createdAt = fecha.parse(_obj.created_at, 'ddd MMM DD HH:mm:ss ZZ YYYY').getTime(); // Thu Apr 30 11:59:47 +0000 2020
newObj.id = _obj.id;
newObj.idStr = _obj.id_str;
newObj.userID = _obj.user.id;
newObj.userIDStr = _obj.user.id_str;
newObj.name = _obj.user.name;
newObj.screenName = _obj.user.screen_name;
return newObj;
}
exports.prepareData = prepareData;
exports.vacuum = () => {
logger.info('>> vacuum:');
return new Promise((resolve, reject) => {
db.run('VACUUM', function(err) {
if (err)
reject(err);
resolve({ 'msg':'Vacuum', 'changes': this.changes });
});
});
};
exports.deleteUpTo = (ms) => {
logger.info('>> deleteUpTo:', ms);
const sql = 'delete from tweets where createdAt < ?';
return new Promise((resolve, reject) => {
db.run(sql, ms, function(err) {
if (err)
reject(err);
resolve({ 'msg':'Rows deleted', 'changes': this.changes });
});
});
};
exports.getAll = (list) => {
logger.info('>> getAll:', list);
const outgoing = [];
// const sql = 'SELECT * FROM tweets order by _id desc limit 20';
const sql = `SELECT * FROM tweets where userID In ( ${list.join(',')} ) order by _id desc limit 20`;
return new Promise((resolve, reject) => {
db.all(sql, [], (err, rows) => {
if (err)
reject(err);
rows.forEach((row) => {
outgoing.push(row);
});
resolve(outgoing) ;
});
});
};
exports.getLatestTweets = (ms) => {
logger.info('>> getAll:', ms);
const outgoing = [];
// const sql = 'SELECT * FROM tweets order by _id desc limit 20';
const ts = (new Date().getTime() - ms) ;
const sql = 'SELECT * FROM tweets where ts>=? order by ts asc';
return new Promise((resolve, reject) => {
db.all(sql, [ts], (err, rows) => {
if (err)
reject(err);
rows.forEach((row) => {
outgoing.push(row);
});
resolve(outgoing) ;
});
});
};
exports.getTopOne = (hash) => {
const sql = 'SELECT * FROM tweets order by _id desc limit 1';
return new Promise((resolve, reject) => {
db.get(sql, [hash], (err, row) => {
if (err)
reject(err);
if (!err) resolve([row]);
});
});
};
exports.getOne = (hash) => {
const sql = 'SELECT * FROM menu WHERE hash = ?';
return new Promise((resolve, reject) => {
db.get(sql, [hash], (err, row) => {
if (err)
reject(err);
if (!err) resolve(row);
});
});
};
exports.getOneShort = (short) => {
const sql = 'SELECT * FROM menu WHERE short = ?';
return new Promise((resolve, reject) => {
db.get(sql, [short], (err, row) => {
if (err)
reject(err);
if (!err) resolve(row);
});
});
};
exports.insertOne = (data) => {
const sql = 'INSERT INTO tweets VALUES (?,?,?,?,?,?,?,?,?,?)';
const tweetObj = prepareData(data);
return new Promise((resolve, reject) => {
db.run(sql, [null, tweetObj.ts, tweetObj.createdAt, tweetObj.id, tweetObj.idStr, tweetObj.userID, tweetObj.userIDStr, tweetObj.name, tweetObj.screenName, tweetObj.tweet], function(err) {
if (err)
reject(err);
resolve({ 'msg':'Row inserted', '_id': this.lastID });
});
});
};
exports.deleteOne = (hash) => {
const sql = 'DELETE FROM menu WHERE hash=?';
return new Promise((resolve, reject) => {
db.run('DELETE FROM menu WHERE hash=?', hash, function(err) {
if (err)
reject(err);
resolve({ 'msg':'Row deleted', 'changes': this.changes });
});
});
};
exports.updateOne = (data) => {
const oldHash = data.hash;
const workObj = prepareData(data);
const sql = `UPDATE menu
SET name = ?, url = ?, md = ?, short = ?, hash = ?, meat = ?, mealtype = ?, lastused = ?
WHERE hash = ?`;
const newData = [workObj.name, workObj.url, workObj.md, workObj.short, workObj.hash, workObj.meat, workObj.mealtype, workObj.lastused, oldHash];
return new Promise((resolve, reject) => {
db.run(sql, newData, function(err) {
if (err)
reject(err);
resolve({ 'msg':'Row updated', 'changes': this.changes });
});
});
};
exports.getRandom = (timestamp) => {
const sql = 'SELECT _id, short, hash, name, meat, mealtype FROM menu where mealtype =1 and lastused<? order by RANDOM()';
const sqlTimestamp = ~~(timestamp / 1000);
return new Promise((resolve, reject) => {
db.all(sql, [sqlTimestamp], (err, rows) => {
if (err)
reject(err);
if (!err) {
const outgoing = [...rows];
resolve(outgoing) ;
}
});
});
};
exports.updateTimestamps = (newTimestamp, items) => {
const sqlTimestamp = ~~(newTimestamp / 1000);
logger.info('>> items', items);
const sql = 'UPDATE menu SET lastused = $lastused WHERE _id = $in';
return new Promise((resolve, reject) => {
db.serialize(() => {
const stmt = db.prepare(sql);
items.forEach((item) => {
logger.info(item);
const newData = { '$lastused':sqlTimestamp, '$in':item };
stmt.run(newData);
});
stmt.finalize((err) => {
if (err)
reject(err);
resolve({ 'msg':'Row updateds' });
});
});
});
};