I’m trying to export a module with async
/await
. Tried other online solutions but none is working for me. Looking for better solution (within db.js
file) if possible.
With below implementation, db1
is always undefined:
// db.js
const mysql = require("mysql");
const environment = require("../environment");
const AWS = require("aws-sdk");
const createAuthToken = async () => {
const signer = new AWS.RDS.Signer();
return await signer.getAuthToken({
credentials: {
region: environment.aws.region,
accessKeyId: environment.aws.accessKeyId,
secretAccessKey: environment.aws.secretAccessKey
},
region: environment.aws.region,
username: environment.mysql.user,
hostname: environment.mysql.host,
port: environment.mysql.port
})
}
exports.db1 = async () => { // How to export db1 using async await
const token = await createAuthToken();
return mysql.createPool({
host: environment.mysql[0].host,
port: environment.mysql[0].port,
user: environment.mysql[0].user,
password: token,
connectionLimit: 10
});
}
this.db1; // I can't use (top-level) await, as my package.json doesn't have type: module and I don't want to add it.
I don’t want to make changes (like adding await) in this file:
// common.query.js
const database = require("../db");
const db1 = database.db1; // db1 is undefined obviously
class CommonQuery {
static executeQuery = () => {
db1.serialize(() => {
db.all(query, param,
(error, rows) => {
if (error) {
logger.error("error occured in executing query !", { error: error }, { service: "common" }, { file: `${__filename}` }, { user: ClaimService.getUser() });
return cb({ message: ERROR_MSG.DB_ERROR });
}
return cb(null, rows);
});
});
}
}
module.exports = CommonQuery ;
// controller.js
const CommonQuery = require("../common.query.js")
CommonQuery.executeQuery();
I don’t want to use db1.then()
syntax, just need better solution with async
/await
.