UNPKG

@avonjs/avonjs

Version:

A fluent Node.js API generator.

161 lines (160 loc) 3.78 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Contracts_1 = require("../Contracts"); class Repository { /** * List of applied conditions. */ wheres = []; /** * List of applied orderings. */ orders = []; /** * List of query modifier callbacks. */ modifiers = []; /** * The transaction instance. */ _transaction; /** * Run a transaction on the storage. */ async transaction(callback) { const trx = await this.prepareTransaction(); // update current transaction this.setTransaction(trx); try { // Execute the callback within the transaction const result = await callback(this, trx); // Commit the transaction if it exists if (trx !== undefined) { await trx.commit(); } return result; } catch (error) { // Rollback the transaction if an error occurs if (trx !== undefined) { await trx.rollback(); } throw error; } } /** * Set the transaction instance. */ setTransaction(transaction) { this._transaction = transaction; return this; } /** * Get the transaction instance. */ getTransaction() { return this._transaction; } /** * Indicates whether the transaction is running or not. */ runningInTransaction() { return this.getTransaction() !== undefined; } /** * Start new transaction. */ async prepareTransaction() { return new (class { commit(value) { return value; } rollback(error) { return error; } })(); } /** * Apply condition('s) to the repository. */ where(where) { const wheres = Array.isArray(where) ? where : [where]; wheres.forEach((where) => this.wheres.push(where)); return this; } /** * Set conditions on the repository. */ setWheres(wheres) { this.wheres = wheres; return this; } /** * Get all conditions from the repository. */ getWheres() { return this.wheres; } /** * Apply condition to repository. */ order(order) { const orders = Array.isArray(order) ? order : [order]; orders.forEach((order) => this.orders.push(order)); return this; } /** * Set orders on the repository. */ setOrders(orders) { this.orders = orders; return this; } /** * Get all orders from the repository. */ getOrders() { return this.orders; } /** * Modify underlying query before execute. */ modify(modifier) { this.modifiers.push(modifier); return this; } /** * Find model for the given key. */ async find(key) { return this.whereKey(key).first(); } /** * Apply primary key condition */ whereKey(key) { return this.where({ key: this.model().getKeyName(), value: key, operator: Contracts_1.Operator.eq, }); } /** * Apply primary key condition */ whereKeys(keys) { return this.where({ key: this.model().getKeyName(), value: keys, operator: Contracts_1.Operator.in, }); } /** * Fill data into model. */ fillModel(result) { const Constructor = this.model().constructor.prototype.constructor; return new Constructor(result); } } exports.default = Repository;