/** * store - abstract class * * @author Björn Hase * @license http://opensource.org/licenses/MIT The MIT License * @link https://gitea.node001.net/HerrHase/urban-filehub.git * */ class Store { /** * * * @param {tableName} * */ constructor(db, tableName) { this._db = db this._tableName = tableName } /** * create row * */ findOneById(id) { return this._db .prepare('SELECT * FROM ' + this._tableName + ' WHERE id = ?') .get(id) } /** * create row * */ remove(id) { return this._db .prepare('DELETE FROM ' + this._tableName + ' WHERE id = ?') .run(id) } /** * * */ update(id, data) { return this._db .prepare('UPDATE ' + this._tableName + ' SET ' + this._prepareUpdateBinding(data) + ' WHERE id = ?') .run(data, id) } /** * * */ create(data) { const result = this._db .prepare('INSERT INTO ' + this._tableName + ' (' + Object.keys(data).join(', ') + ') VALUES (' + this._prepareInsertBinding(data) + ')') .run(data) if (!result.lastInsertRowid) { throw new Error('Store / missing id after created data') } return result.lastInsertRowid } /** * run through object and add key to string for * binding parameters for insert * * @param {object} data * @return {string} */ _prepareInsertBinding(data) { let result = '' let length = Object.keys(data).length let index = 0 for (const key in data) { result += '@' + key if (index++ < (length - 1)) { result += ', ' } } return result } /** * run through object and add key to string for * binding parameters for update * * @param {object} data * @return {string} */ _prepareUpdateBinding(data) { let result = '' let length = Object.keys(data).length let index = 0 for (const key in data) { result += key + ' = @' + key if (index++ < (length - 1)) { result += ', ' } } return result } } export default Store