iagate-querykit
Version:
QueryKit: lightweight TypeScript query toolkit with models, views, triggers, events, scheduler and adapters (better-sqlite3).
65 lines (64 loc) • 2.09 kB
JavaScript
import { QueryBuilder } from './query-builder';
import { runSeed } from './seed';
export class Model {
static tableName;
static banks;
banks;
fillable = [];
guarded = ['id', 'created_at', 'updated_at'];
static query() {
const qb = new QueryBuilder(this.tableName);
const banks = this.banks;
if (banks && banks.length)
qb.bank(banks);
return qb;
}
static withRelations(selector) {
const qb = this.query().relationship(selector);
return qb;
}
static async seed(dataOrSeed, opts = {}) {
return runSeed(this.tableName, dataOrSeed, opts);
}
bank(bankOrBanks) {
this.banks = Array.isArray(bankOrBanks) ? bankOrBanks : [bankOrBanks];
return this;
}
applyBanks(qb) {
if (this.banks && this.banks.length)
return qb.bank(this.banks);
return qb;
}
fill(attributes) {
const fillableAttributes = this.getFillableAttributes(attributes);
Object.assign(this, fillableAttributes);
}
getFillableAttributes(attributes) {
if (this.fillable.length > 0) {
const result = {};
this.fillable.forEach(key => { if (attributes[key] !== undefined)
result[key] = attributes[key]; });
return result;
}
if (this.guarded.length > 0) {
const result = { ...attributes };
this.guarded.forEach(key => { delete result[key]; });
return result;
}
return attributes;
}
save() {
const queryBase = this.constructor.query();
const query = this.applyBanks(queryBase);
const attributes = this.getFillableAttributes(this);
if (this.id) {
return query.where('id', '=', this.id).update(attributes).make();
}
return query.insert(attributes).make();
}
delete() {
const queryBase = this.constructor.query();
const query = this.applyBanks(queryBase);
return query.where('id', '=', this.id).delete().make();
}
}