You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
109 lines
2.2 KiB
109 lines
2.2 KiB
/**
|
|
* store - abstract class
|
|
*
|
|
* @author Björn Hase <me@herr-hase.wtf>
|
|
* @license hhttps://www.gnu.org/licenses/gpl-3.0.en.html GPL-3
|
|
* @link https://git.node001.net/HerrHase/signpost.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 = ?')
|
|
.run(id)
|
|
}
|
|
|
|
/**
|
|
* create row
|
|
*
|
|
*/
|
|
remove(id) {
|
|
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(id, data)
|
|
}
|
|
|
|
/**
|
|
*
|
|
*
|
|
*/
|
|
create(data) {
|
|
return this._db.prepare('INSERT INTO ' + this._tableName + ' (' + Object.keys(data).join(', ') + ') VALUES (' + this._prepareInsertBinding(data) + ')')
|
|
.run(data)
|
|
}
|
|
|
|
/**
|
|
* 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
|