UNPKG

genuinex-screen-sync-server

Version:
149 lines (122 loc) 2.61 kB
/** * @format */ "use strict"; const path = require("path"); const sqlite = require("sqlite3"); class Model { constructor() { let dbPath = ":memory:"; if (process.env.NODE_ENV === "production") { dbPath = path.resolve(__dirname, "../genuinex.sqlite3"); } console.log("connecting to this.db." + dbPath); this.db = new sqlite.Database(dbPath); this.db.run( "CREATE TABLE IF NOT EXISTS trends (id TEXT PRIMARY KEY NOT NULL, value INTEGER DEFAULT 0)" ); } list(cb) { this.db.all("SELECT * FROM trends", (err, rows) => { if (err) { return cb(err, []); } const trends = {}; rows.forEach(row => { trends[row.id] = row.value; }); cb(err, trends); }); } create(id, value, cb) { if (!id) { return cb(new Error("invalid id")); } if (!this.isValid(value)) { return cb(new Error("invalid value")); } this.db.run( "INSERT INTO trends VALUES ($id, $value)", { $id: id, $value: value }, err => { if (err) { return cb(err, null); } this.get(id, cb); } ); } get(id, cb) { if (!id) { return cb(new Error("invalid id")); } this.db.get( "SELECT * FROM trends WHERE id = $id", { $id: id }, cb ); } update(id, value, cb) { if (!id) { return cb(new Error("invalid id")); } if (!this.isValid(value)) { return cb(new Error("value must be a number")); } this.db.run( "UPDATE trends SET value = $value WHERE id = $id", { $id: id, $value: value }, err => { if (err) { return cb(err, null); } this.get(id, cb); } ); } increment(id, cb) { if (!id) { return cb(new Error("invalid id")); } this.get(id, (err, row) => { if (err) { return cb(err, null); } if (!row) { this.create(id, 1, cb); } else { this.db.run( "UPDATE trends SET value = value + 1 WHERE id = $id", { $id: id }, err => { if (err) { return cb(err, null); } this.get(id, cb); } ); } }); } delete(id, cb) { if (!id) { return cb(new Error("invalid id")); } this.db.run("DELETE FROM trends WHERE id = $id", { $id: id }, cb); } isValid(value) { if (isNaN(value)) { return false; } return true; } } module.exports = new Model();