Is there a method for establishing a connection to oracledb using TypeScript ES6 class and module?

My goal is to implement an Oracle connection using Typescript ES6 Class module. I have successfully installed the @types/oracledb package and oracledb package, with the Jasmin framework used in my project.

Below is the code I have implemented:


import * as oracledb from 'oracledb';

export class ConnectionDAO{
/**
 * Connection Variable Declaration
 */
conn;

/**
 * Result Variable Declaration
 */
result;

/**
 *
 * Creates an instance of CommercialDAO.
 * To Initiate Connection and Make the connection utilized by @memberof CommercialDAO
 * @memberof CommercialDAO
 */
constructor() {
   this.conn = oracledb.getConnection({
        user: "commercial",
        password: "oracle",
        connectString: "localhost/COMMERCIALDB"
      }); 
}

public getRwCnt() {
    return new Promise(async function(resolve, reject) {
        try {
            let result = this.conn.execute('SELECT TESTCASEID FROM EXECUTE_TESTCASE');
            resolve(this.result.rows.length);
        } catch (err) { // catches errors in getConnection and the query
          reject(err);
        } 
        this.conn.release();
      });
}
}

Error:

TypeError: this.conn.execute is not a function

The issue here is that the connection itself is not being stored in the 'this.conn' variable as expected.

I am looking for alternative solutions to achieve this without using promises and async functions. Any other suggestions on how to resolve this? Your valuable input and sample snippet would be greatly appreciated.

Answer №1

The main cause of the error you are facing:

TypeError: this.conn.execute is not a function

Occurs because 'this.conn' is most likely undefined. To address this issue, consider adding a check like the following:

public getRwCnt() {
  if(this.conn === undefined){
    console.log("The connection is not ready yet.");
    return;
... // Continue with your function implementation
}

However, simply spotting the problem won't provide you with the reason behind it.

The root cause lies in the fact that your constructor is entirely synchronous. You might want to introduce a function that waits for the constructor to complete its execution.

Here's an altered version that resolves this concern:

import * as OracleDB from 'oracledb';

export class ConnectionDAO {
  /**
   * Declaration of Connection Variable
   */
  public conn: OracleDB.IConnection;
  public connProm: OracleDB.IPromise<void>;

  /**
   * Declaration of Result Variable
   */
  result;

  /**
   *
   * Initiates CommercialDAO - establishes and utilizes a connection 
   * @memberof CommercialDAO
   */
  constructor() {
    this.connProm = OracleDB.getConnection({
      user: "hr",
      password: "hr",
      connectString: "localhost/XEPDB1"
    }).then(async (connection: OracleDB.IConnection) => {
      console.log("Successfully created connection in constructor")
      this.conn = connection;
    }).catch((err: any) => {
      console.error(err.message);
    });
    console.log(" - Checking Connection state at end of constructor", {conn: this.conn} , {connProm: this.connProm} );
  }

  public getRwCnt() {
    let me = this;
    return new Promise(async function (resolve, reject) {
      try {
        console.log(" - Checking Connection state BEFORE waiting",{conn: me.conn} , {connProm: me.connProm} );
        await me.connProm;
        console.log(" - Checking Connection state AFTER waiting",{connServerVersion: me.conn.oracleServerVersion } , {connProm: me.connProm} );
        let result = await me.conn.execute('SELECT count(*) FROM employees');
        resolve(result.rows);
      } catch (err) { // catches errors in getConnection and the query
        console.log("[Error] occurred? - calling reject",err);
        reject(err);
      }
      if(me.conn) // Release only if it has been set
        me.conn.release();
    });
  }
}

const d = new ConnectionDAO();

d.getRwCnt()
  .then((result)=>{console.log("RowCount",result)})
  .catch((err)=>{console.error("Promise rejected - ",err)})

console.log("Constructor object returned");

If executed with ts-node, the following outcome is obtained:

 - Checking Connection state at end of constructor { conn: undefined } { connProm: Promise { <pending> } }
 - Checking Connection state BEFORE waiting { conn: undefined } { connProm: Promise { <pending> } }
Constructor object returned
Successfully created connection in constructor
 - Checking Connection state AFTER waiting { connServerVersion: 1804000000 } { connProm: Promise { undefined } }
RowCount [ [ 107 ] ]

Answer №2

It appears that the this keyword is being misused in the function getRwCnt().

Remember, each function in JavaScript has its own this context.

Option 1: Assign the initial this value to another variable within the function:

public getRwCnt() {
    let me = this; 
    return new Promise(async function(resolve, reject) {
        try {
            let result = me.conn.execute('SELECT TESTCASEID FROM EXECUTE_TESTCASE');
            resolve(this.result.rows.length);
        } catch (err) { // catches errors in getConnection and the query
          reject(err);
        } 
        me.conn.release();
      });

Option 2: Utilize ES6 Arrow functions:

public getRwCnt() {

        return new Promise(async (resolve, reject) => {
            try {
                let result = this.conn.execute('SELECT TESTCASEID FROM EXECUTE_TESTCASE');
                resolve(this.result.rows.length);
            } catch (err) { // catches errors in getConnection and the query
              reject(err);
            } 
            this.conn.release();
          });

Answer №3

After implementing your recommended solution, I encountered an issue where TypeScript does not seem to be waiting for the call to await me.connectionPromise. Additionally, there is uncertainty regarding whether the connection was successful or not as indicated by the output below.

Upon investigating further, I discovered that the following lines were missing from your provided code snippet:

Connection finally created in constructor
 - Dumping Connection state AFTER waiting { connServerVersion: 1804000000 } { connProm: Promise { undefined } }
RowCount [ [ 107 ] ]

Answer №4

Encountered a similar problem. I solved it by updating my import statement:

import * as oracledb from 'oracledb';

to

import oracledb from 'oracledb';

This resolved the issue for me.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In Angular 4, you can easily preselect multiple options in a mat-select dropdown by passing an

Seeking assistance with setting the options of a mat-select in Angular 4. The issue at hand is as follows: 1. Initially, there are two variables: options and checkedOptions options: string[]; checkedOptions: string[] //Retrieved from the database; 2. T ...

NGXS no longer functions properly when upgrading to Angular 9 and enabling Ivy

I am currently in the process of upgrading my Angular application to version 9. I have encountered an issue where everything runs smoothly when Ivy is disabled, but enabling Ivy causes the application's serve task to not finish correctly: Here is a s ...

Property element does not exist in this basic TypeScript project

I'm diving into my initial TypeScript project and encountering an issue with the "style". I attempted to utilize style!, create an if(changeBackgroundColor){}, but without success. let changeBackgroundColor = document.querySelectorAll('[data-styl ...

Error encountered while compiling React application: Module build unsuccessful due to failure in ./node_modules/babel-loader/lib/index.js

Having an issue while trying to compile a React app. After pulling the repo from Github, running yarn install, and then compiling it, I encountered the following error: Module build failed (from ./node_modules/babel-loader/lib/index.js) SyntaxError: {file_ ...

What is the best way to incorporate TypeScript variables into CSS files?

In my Angular project, I am aiming to utilize a string defined in Typescript within a CSS file. Specifically, I want to set the background image of a navbar component using a path retrieved from a database service. Although I came across suggestions to use ...

Aliases for NPM packages and TypeScript declaration files

I am in need of two separate versions of a package, and fortunately with npm 6.9.0 I can easily accomplish that now. My dilemma is this: the package comes with type definitions. However, when I create an alias for this package and refer to it using the al ...

Unable to access default route

My application is structured as follows: app.module.ts const routes: Routes = [ { path: '', loadChildren: './modules/main/main.module#MainModule' }, ]; @NgModule({ declarations: [ AppComponent, ] ...

What is the best way to import and export modules in Node.js when the module names and directories are given as strings?

Here is the structure of my folder: modules module-and index.js module-not index.js module-or index.js module-xor index.js moduleBundler.js The file I'm currently working on, moduleBundler.js, is re ...

Using Typescript: Compiling specific files within a directory

According to the documentation for typescript, we have the option in tsconfig.json to manage input files using either the files property where all files are listed, or with the exclude property. I have organized all my source files within a directory named ...

How to retrieve a stored value using Ionic 3 native storage

Hey there, I recently attempted to implement code from the Native Storage plugin documentation found at this link: Native Storage import { NativeStorage } from '@ionic-native/native-storage'; constructor(private nativeStorage: NativeStorag ...

How to Define Intersection Type with Symbol in TypeScript?

I'm currently working on a helper function that associates a Symbol with a value. function setCustomSymbol<S extends symbol, T>(symbol: S, data: T, defaultValue: any = true): S & T { /*...*/ } The issue I'm facing is trying to instruc ...

What methods are available to enhance the appearance of a string with TypeScript Angular in Python?

Looking to enhance the appearance of a Python string for display on an HTML page. The string is pulled from a database and lacks formatting, appearing as a single line like so: for count in range(2): global expression; expression = 'happy'; sto ...

Transitioning from Oracle's select syntax to Postgres can be a

I'm currently in the process of translating Oracle Syntax to Postgres SELECT MSN_INT_ID, MO_INT_ID, 'Y' "AIRMOVE" FROM MISSION_OBJECTIVE WHERE MO_MSN_CLASS_CD = 'AMV' GROUP BY MSN_INT_ID, MO_INT_ID T ...

Is there a way to verify if the size of an array retrieved from an API request has been altered?

Is there a way to compare the length of the array returned after an API refresh call with the previous value? For instance: let currentLength; let previousLength; ngOnInit() { this.dataService.getData().subscribe(data => { this.data = data; t ...

Transforming a mongodb operation into an asynchronous function using await and async syntax

After calling the function to retrieve data from MongoDB, an undefined error occurs. It is suspected that converting the function to an async/await function may resolve this issue. However, there is uncertainty on how to make this conversion without disrup ...

Creating a custom pipe that converts seconds to hours and minutes retrieved from an API can be achieved by implementing a transformation function

Can someone please provide guidance on creating a custom pipe in Angular 8 that converts seconds to hours and minutes? Thank you. <div class="col-2" *ngFor="let movie of moviesList"> <div class="movie"> {{ movie.attributes.title }} ...

Vue alert: Component resolution failed while attempting to create a global component

I am new to Vue Typescript and I have been encountering an issue while trying to create global components. I received a warning and the component did not load on the template. Here is how I attempted to create global components: App.vue import { createApp ...

Issues with typescript compiler when using React-beautiful-dnd

I recently updated react and react-beautiful-dnd to the newest versions and now I am encountering many type errors in my code: {sortedDimensions.map((dimension: any, index: number) => ( <Draggable key={index} ...

Having trouble pushing to an array in Angular typescript? It seems to be returning as undefined

As a newcomer to Angular with a basic understanding of JavaScript, I am attempting to create a program that can solve Sudoku puzzles. In a 9x9 grid, there are a total of 81 points or squares. To efficiently check for violations of Sudoku rules - no repeati ...

Encountered an eas error during Android build process

When I try to execute the command "eas build --platform android" I encounter the following error message: "✖ Build failed ...