UNPKG

oracle-procedure

Version:

Pacote responsável por padronizar a chamada de procedure com o typeorm e o oracledb

107 lines 3.54 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Procedure = void 0; const typeorm_1 = require("typeorm"); const oracledb = require("oracledb"); class Procedure { constructor(connection) { this.connection = connection; this.name = null; this.inputs = {}; this.outputs = {}; this.orderedParameters = []; } async execute() { try { switch (true) { case this.connection instanceof typeorm_1.DataSource: return await this.executeDataSource(); case this.connection instanceof oracledb.Connection: return await this.executeOracle(); default: throw new Error("Conexão recebida não é suportada!"); } } catch (error) { throw error; } } async executeOracle() { try { const runner = await this.connection.execute(this.procedure, this.fields); if (!runner.outBinds) throw Error(`Execução da procedure ${this.constructor.name} não foi concluída`); const values = Object.values(runner.outBinds); return await this.getData(values); } finally { this.connection.close(); } } async executeDataSource() { const queryRunner = this.connection.createQueryRunner(); try { await queryRunner.connect(); const runner = await queryRunner.query(this.procedure, this.bindings); return await this.getData(runner); } finally { queryRunner.release(); } } async getData(runner) { const data = {}; Object.entries(this.outputs).forEach(([key, value], index) => { if (value.type == oracledb.CURSOR) data[key] = this.getDataFromCursor(runner[index]); else data[key] = runner[index]; }); for (const key in data) { if (data[key] instanceof Promise) { data[key] = await data[key]; } } return data; } async getDataFromCursor(cursor) { const columns = cursor.metaData.map((column) => column.name); const data = []; let row = null; while ((row = await cursor.getRow())) { const line = {}; columns.forEach((column, index) => { line[column.toLowerCase()] = Array.isArray(row) ? row[index] : row[column]; }); data.push(line); } await cursor.close(); return data; } get bindings() { return Object.values(this.fields); } get fields() { const orderedParameters = {}; const fields = Object.assign(this.inputs, this.outputs); this.orderedParameters.forEach((key) => { orderedParameters[key] = fields[key]; }); return orderedParameters; } get parameters() { const keys = Object.keys(this.fields); if (!keys) return; return keys.map((field) => `:${field}`).join(", "); } get procedure() { if (!this.name) throw new ReferenceError(`A propriedade name não está definida em ${this.constructor.name}`); return `BEGIN ${this.name}(${this.parameters}); END;`; } } exports.Procedure = Procedure; //# sourceMappingURL=Procedure.js.map