silvie
Version:
Typescript Back-end Framework
106 lines (96 loc) • 2.83 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _query_builder = _interopRequireDefault(require("./query_builder"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
class Model extends _query_builder.default {
/**
* Fetch all records from the table
*/
static async all() {
return this.castAll(await this.baseQueryBuilder.get());
}
/**
* Find a record in the table with the given id
* @param id
*/
static async find(id) {
const result = await this.primaryKeyCondition(this.baseQueryBuilder, null, [id]).first();
return result ? this.cast(result) : null;
}
static async findAll(...ids) {
const results = await this.primaryKeyCondition(this.baseQueryBuilder, null, ids).get();
return results.length > 0 ? this.castAll(results) : [];
}
/**
* Insert a single record into the table and return with either created record or InsertedId
* @param data
* @param shouldReturn Specify to return the created record or not, defaults to true
*/
static async create(data, shouldReturn = true) {
const [insertId] = await this.baseQueryBuilder.insert([data]);
if (shouldReturn) {
if (this.primaryKey instanceof Array) {
return this.find(this.primaryKey.map(key => data[key]));
}
return this.find(insertId);
}
return insertId;
}
/**
* Fill this instance with the provided data
* @param data
*/
fill(data) {
Object.keys(data).forEach(key => {
this[key] = data[key];
});
}
/**
* Retrieve a fresh copy of this instance from the database
*/
async fresh() {
return this.constructor.cast(await this.baseQueryBuilder.first());
}
/**
* Refresh the current instance from the database
*/
async refresh() {
const result = await this.baseQueryBuilder.first();
Object.assign(this, result);
}
/**
* Update the current instance with the provided data
* @param data
* @param silent Weather to refresh the update timestamp or not
*/
async update(data, silent = false) {
const result = await this.baseQueryBuilder.update(data, silent);
if (result.affectedRows > 0) {
this.fill(data);
}
return result;
}
/**
* Delete the current instance (uses soft delete if it is enabled in model)
*/
delete() {
return this.baseQueryBuilder.delete(this.constructor.useSoftDeletes);
}
/**
* Delete the current instance
*/
forceDelete() {
return this.baseQueryBuilder.delete();
}
/**
* Save the changes of current instance in the database
* @param silent Weather to refresh the update timestamp or not
*/
save(silent = false) {
return this.update(this, silent);
}
}
var _default = exports.default = Model;