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.
123 lines
2.5 KiB
123 lines
2.5 KiB
/**
|
|
* store - abstract class
|
|
*
|
|
* @author Björn Hase <me@herr-hase.wtf>
|
|
* @license http://opensource.org/licenses/MIT The MIT License
|
|
* @link https://gitea.node001.net/HerrHase/urban-filehub.git
|
|
*
|
|
*/
|
|
|
|
abstract class Store {
|
|
|
|
protected db: string
|
|
protected tableName: string
|
|
|
|
/**
|
|
*
|
|
*
|
|
* @param {tableName}
|
|
*
|
|
*/
|
|
constructor(db: object, tableName?: string) {
|
|
this.db = db
|
|
this.tableName = tableName
|
|
}
|
|
|
|
/**
|
|
* create row
|
|
*
|
|
*/
|
|
findOneById(id: integer): object {
|
|
return this.db
|
|
.query('SELECT * FROM ' + this.tableName + ' WHERE id = $id')
|
|
.get({
|
|
'$id': id
|
|
})
|
|
}
|
|
|
|
/**
|
|
* create row
|
|
*
|
|
*/
|
|
create(data: object): integer {
|
|
this.db
|
|
.query('INSERT INTO ' + this.tableName + ' (' + Object.keys(data).join(', ') + ') VALUES (' + this.prepareInsertBinding(data) + ')')
|
|
.run(this.prepareData(data))
|
|
|
|
return this.db.query('SELECT last_insert_rowid()').get()['last_insert_rowid()']
|
|
}
|
|
|
|
/**
|
|
* update row
|
|
*
|
|
*/
|
|
update(id: integer, data: object): void {
|
|
this.db
|
|
.query('UPDATE ' + this.tableName + ' SET ' + this.prepareUpdateBinding(data) + ' WHERE id = $id')
|
|
.run(this.prepareData(Object.assign(data, {
|
|
'id': id
|
|
})))
|
|
}
|
|
|
|
/**
|
|
* create row
|
|
*
|
|
*/
|
|
remove(id: integer): remove {
|
|
this.db
|
|
.query('DELETE FROM ' + this.tableName + ' WHERE id = $id')
|
|
.run({
|
|
$id: id
|
|
})
|
|
}
|
|
|
|
/**
|
|
*
|
|
*/
|
|
prepareData(data: object) {
|
|
const results = {}
|
|
|
|
for (const key in data) {
|
|
results['$' + key] = data[key]
|
|
}
|
|
|
|
return results
|
|
}
|
|
|
|
/**
|
|
* run through object and add key to string for
|
|
* binding parameters for insert
|
|
*
|
|
* @param {object} data
|
|
* @return {string}
|
|
*/
|
|
prepareInsertBinding(data: array) {
|
|
let result = []
|
|
|
|
for (const key in data) {
|
|
result.push('$' + key)
|
|
}
|
|
|
|
return result.join(', ')
|
|
}
|
|
|
|
/**
|
|
* run through object and add key to string for
|
|
* binding parameters for update
|
|
*
|
|
* @param {object} data
|
|
* @return {string}
|
|
*/
|
|
prepareUpdateBinding(data: array) {
|
|
let result = []
|
|
|
|
for (const key in data) {
|
|
result.push(key + ' = $' + key)
|
|
}
|
|
|
|
return result.join(', ')
|
|
}
|
|
}
|
|
|
|
export default Store
|