How can I perfectly work with Oracle DB in my Node.js project

Viewed 1594

I am currently working on a web site using Angular, Node.Js, express and an Oracle database.

I'm still not familiar with all this technologies and I'm doing my best! My problem is the Oracle database connection can't be exported. I searched about this and I think it's a promise thing. The only solution I found is to connect to the database every time I use a new SQL query which is impossible for me because the project is big.

Is there any method I can use to make the database connection in a separate file and export it when I need it?

1 Answers

With a multi-user app, you should use a connection pool. You open it at app start, and then access it as needed - you don't have to pass anything around.

If you open the connection pool in your initialization routine:

await oracledb.createPool({
  user: dbConfig.user,
  password: dbConfig.password,
  connectString: dbConfig.connectString
});
console.log('Connection pool started');

then any other module that needs a connection can simply do:

conn = await oracledb.getConnection();
result = await conn.execute(statement, binds, opts);
await conn.close();

Read up on connection pools and sizing and threads in the node-oracledb documentation on Connection Pooling.

Also see the series Build REST APIs for Node.js and its code https://github.com/oracle/oracle-db-examples/tree/master/javascript/rest-api. In particular, look at database.js.

Related