简体   繁体   中英

is there any way to Connect oracledb using typescript ES6 class and module?

i'm trying to implement oracle connection using Typescript ES6 Class module.

i have installed @types/oracledb package as well as oracledb package. Jasmin framework is used.

Below are my code which 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

But in this code connection itself not getting stored in 'this.conn' variable.

is there anyway to avoid promises and async function? Is there any other solution to achieve this? Please provide you valuable solution and suggestions. Expecting sample snippet.

The actual reason for your error

TypeError: this.conn.execute is not a function

Is because the this.conn is most likely undefined. Add a check like this.

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

But this will only highlight that you have a problem, but not tell you why.

The reason is that your constructor is strictly synchronous. Consider having a function that waits for the constructor to finish.

Here is a version that works:

import * as OracleDB from 'oracledb';

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

  /**
   * Result Variable Declaration
   */
  result;

  /**
   *
   * Creates an instance of CommercialDAO.
   * To Initiate Connection and Make the connection utilized by @memberof CommercialDAO
   * @memberof CommercialDAO
   */
  constructor() {
    this.connProm = OracleDB.getConnection({
      user: "hr",
      password: "hr",
      connectString: "localhost/XEPDB1"
    }).then(async (connection: OracleDB.IConnection) => {
      console.log("Connection finally created in constructor")
      this.conn = connection;
    }).catch((err: any) => {
      console.error(err.message);
    });
    console.log(" - Dumping Connection state in the end of the constructor", {conn: this.conn} , {connProm: this.connProm} );
  }

  public getRwCnt() {
    let me = this;
    return new Promise(async function (resolve, reject) {
      try {
        console.log(" - Dumping Connection state BEFORE waiting",{conn: me.conn} , {connProm: me.connProm} );
        await me.connProm;
        console.log(" - Dumping 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] happened? - calling reject",err);
        reject(err);
      }
      if(me.conn) // Only release it it if it actually is 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("Object constructor returned");

Running this with ts-node gives this result

 - Dumping Connection state in the end of the constructor { conn: undefined } { connProm: Promise { <pending> } }
 - Dumping Connection state BEFORE waiting { conn: undefined } { connProm: Promise { <pending> } }
Object constructor returned
Connection finally created in constructor
 - Dumping Connection state AFTER waiting { connServerVersion: 1804000000 } { connProm: Promise { undefined } }
RowCount [ [ 107 ] ]

Seems you use the this with wrong way in function getRwCnt() .

Remember each function in JavaScript has self this .

Option 1 Assign the top this to another variable at the beginning of 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 Use ES6 Arrow function

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();
          });

I tried your solution, but looks like typescript is not waiting for the call await me.connectionPromise; Also, not sure if the connection is successful or not. I am getting below output.

Inside constructor
get Connection executed....
 - Dumping Connection state in the end of the constructor { conn: undefined } { connProm: Promise { <pending> } }
Inside getRowNumbers function call....
Connection state BEFORE waiting:  { conn: undefined } { connectionPromise: Promise { <pending> } }
Object constructor returned

Somehow below output lines in your code are missing for me.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM