UNPKG

lia-mysql

Version:

JavaScript library of data standards.

75 lines 2.44 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Transaction = void 0; const operator_1 = require("./operator"); class Transaction extends operator_1.Operator { constructor(pool) { super(); this.pool = pool; this.pool2 = pool.promise(); } async getConnection() { if (!this.pool2) { throw new Error('This MysqlTransaction has been released!'); } this.connection = await this.pool2.getConnection(); if (!this.connection) { throw new Error('This MysqlTransaction has no connection!'); } return this.connection; } async release() { this.pool2?.releaseConnection(this.connection); this.connection = null; } async beginTransaction() { await this.getConnection(); await this.connection?.beginTransaction(); return this; } async query(sql, params) { await this.getConnection(); if (!params) { params = []; } return new Promise((resolve_all, reject_all) => { this.connection ?.query(sql, params ? params : []) .then(([rows, fields]) => { resolve_all(rows); }) .catch((ex) => { reject_all(ex); }); }); } async queries(sqls) { await this.getConnection(); // eslint-disable-next-line no-async-promise-executor return new Promise(async (resolve_all, reject_all) => { try { let results = []; try { for (const sql of sqls) { // eslint-disable-next-line no-unsafe-optional-chaining let [rows] = await this.connection?.query(sql.sql, sql.params ? sql.params : []); results.push(rows); } await this.connection?.commit(); this.connection = null; } catch (e) { await this.connection?.rollback(); this.connection = null; reject_all(e); } resolve_all(results); } catch (e) { reject_all(e); } }); } } exports.Transaction = Transaction; //# sourceMappingURL=transaction.js.map