import { Injectable } from '@nestjs/common'; import { OracleDBService } from 'src/db/db.service'; import * as oracledb from 'oracledb' import { InsertRegionsDto, UpdateRegionDto } from './region.dto'; @Injectable() export class RegionService { constructor(private readonly oracleDBService: OracleDBService) { } async insertRegions(body: InsertRegionsDto) { let connection; try { connection = await this.oracleDBService.getConnection() if (!connection) { throw new Error('No DB Connected') } const result = await connection.execute( `BEGIN USCIB_Managed_Pkg.InsertNewRegion(:p_region,:p_name,:p_cursor); END;`, { p_region: { val: body.p_region, type: oracledb.DB_TYPE_VARCHAR }, p_name: { val: body.p_name, type: oracledb.DB_TYPE_VARCHAR }, p_cursor: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT } }, { outFormat: oracledb.OUT_FORMAT_OBJECT } ); await connection.commit(); let fres = await result.outBinds.p_cursor.getRows(); return fres } catch (err) { return { error: err.message } } finally { } } async updateRegions(body: UpdateRegionDto) { let connection; try { connection = await this.oracleDBService.getConnection() if (!connection) { throw new Error('No DB Connected') } const result = await connection.execute( `BEGIN USCIB_Managed_Pkg.UpdateRegion(:p_regionID,:p_name,:p_cursor); END;`, { p_regionID: { val: body.p_regionID, type: oracledb.DB_TYPE_NUMBER }, p_name: { val: body.p_name, type: oracledb.DB_TYPE_VARCHAR }, p_cursor: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT } }, { outFormat: oracledb.OUT_FORMAT_OBJECT } ); await connection.commit(); let fres = await result.outBinds.p_cursor.getRows(); return fres } catch (err) { return { error: err.message } } finally { } } async getRegions() { let connection; let rows = []; try { try { connection = await this.oracleDBService.getConnection() } catch (err) { console.log("DB ERROR: ", err); return { error: "Error while connecting to DB" } } const result = await connection.execute( `BEGIN USCIB_Managed_Pkg.GetRegions(:p_cursor); END;`, { p_cursor: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT } }, { outFormat: oracledb.OUT_FORMAT_OBJECT } ); if (result.outBinds && result.outBinds.p_cursor) { const cursor = result.outBinds.p_cursor; let rowsBatch; do { rowsBatch = await cursor.getRows(100); rows = rows.concat(rowsBatch); } while (rowsBatch.length > 0); await cursor.close(); } else { throw new Error('No cursor returned from the stored procedure'); } return rows; } catch (err) { return { error: err.message } } finally { } } }