Cameron Diver 1b0fd82f51
Convert db module to typescript
Also had to change config module to bind `.this` value, due to
differences in setup.

Change-type: patch
Signed-off-by: Cameron Diver <cameron@resin.io>
2018-06-18 13:39:08 +01:00

67 lines
1.3 KiB
TypeScript

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;
class DB {
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> {
return this.knex('knex_migrations_lock').update({ is_locked: 0})
.catch(() => { return; })
.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,
id: number | { [key: string]: string},
trx?: Knex.Transaction,
): Bluebird<any> {
const knex = trx || this.knex;
return knex(modelName).update(obj).where(id)
.then((n: number) => {
if (n === 0) {
return knex(modelName).insert(obj);
}
});
}
public transaction(cb: DBTransactionCallback): Bluebird<Knex.Transaction> {
return this.knex.transaction(cb);
}
}
export = DB;