2018-06-11 22:18:50 +00:00
|
|
|
import * as Bluebird from 'bluebird';
|
|
|
|
import * as Knex from 'knex';
|
|
|
|
import * as path from 'path';
|
|
|
|
|
|
|
|
import * as constants from './lib/constants';
|
|
|
|
|
|
|
|
interface DBOpts {
|
|
|
|
databasePath?: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
type DBTransactionCallback = (trx: Knex.Transaction) => void;
|
|
|
|
|
2018-12-20 11:47:17 +00:00
|
|
|
export type Transaction = Knex.Transaction;
|
|
|
|
|
|
|
|
export class DB {
|
2018-06-11 22:18:50 +00:00
|
|
|
private databasePath: string;
|
|
|
|
private knex: Knex;
|
|
|
|
|
|
|
|
public constructor({ databasePath }: DBOpts = {}) {
|
|
|
|
this.databasePath = databasePath || constants.databasePath;
|
|
|
|
this.knex = Knex({
|
|
|
|
client: 'sqlite3',
|
|
|
|
connection: {
|
|
|
|
filename: this.databasePath,
|
|
|
|
},
|
|
|
|
useNullAsDefault: true,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
public init(): Bluebird<void> {
|
2018-11-02 14:17:58 +00:00
|
|
|
return this.knex('knex_migrations_lock')
|
|
|
|
.update({ is_locked: 0 })
|
|
|
|
.catch(() => {
|
|
|
|
return;
|
|
|
|
})
|
2018-06-11 22:18:50 +00:00
|
|
|
.then(() => {
|
|
|
|
return this.knex.migrate.latest({
|
|
|
|
directory: path.join(__dirname, 'migrations'),
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
public models(modelName: string): Knex.QueryBuilder {
|
|
|
|
return this.knex(modelName);
|
|
|
|
}
|
|
|
|
|
|
|
|
public upsertModel(
|
|
|
|
modelName: string,
|
|
|
|
obj: any,
|
2019-01-23 16:30:43 +00:00
|
|
|
id: number | Dictionary<unknown>,
|
2018-06-11 22:18:50 +00:00
|
|
|
trx?: Knex.Transaction,
|
|
|
|
): Bluebird<any> {
|
|
|
|
const knex = trx || this.knex;
|
|
|
|
|
2018-11-02 14:17:58 +00:00
|
|
|
return knex(modelName)
|
|
|
|
.update(obj)
|
|
|
|
.where(id)
|
2018-06-11 22:18:50 +00:00
|
|
|
.then((n: number) => {
|
|
|
|
if (n === 0) {
|
|
|
|
return knex(modelName).insert(obj);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
public transaction(cb: DBTransactionCallback): Bluebird<Knex.Transaction> {
|
|
|
|
return this.knex.transaction(cb);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-20 11:47:17 +00:00
|
|
|
export default DB;
|