menuserver/server/lib/dbmanager.js
Martin Donnelly 9e2c07ba38 init
2019-12-11 00:07:07 +00:00

109 lines
2.5 KiB
JavaScript

const db = require('../lib/connect');
const _ = require('lodash');
const shortHash = require('short-hash');
// exports.create = (req, res) => {
function prepareData(_obj) {
const newObj = Object.assign({}, _obj);
newObj.short = _.kebabCase(newObj.name);
newObj.hash = shortHash(newObj.name);
return newObj;
}
exports.getAll = () => {
const outgoing = [];
const sql = 'SELECT _id, short, hash, name, meat, mealtype FROM menu';
return new Promise((resolve, reject) => {
db.all(sql, [], (err, rows) => {
if (err)
reject(err);
rows.forEach((row) => {
outgoing.push(row);
});
resolve(outgoing) ;
});
});
};
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 menu VALUES (?,?,?,?,?,?,?,?,?)';
const workObj = prepareData(data);
return new Promise((resolve, reject) => {
db.run(sql, [null, workObj.name, workObj.url, workObj.md, workObj.short, workObj.hash, workObj.meat, workObj.mealtype, 0], 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 });
});
});
};