Basically using Nodejs I connect to mysql and create a pool using below code which works fine,
db.js
const mysql = require("mysql")
exports.database = mysql.createPool({
host: "host",
port: 3360,
user: "user",
password: "password", // hard-coded password
connectionLimit: 10
});
products.query.js
const db= require("../db").database ; // importing connection pool
class ProductsQuery {
static postProducts(id, cb) {
await db.getConnection(...) // This works perfectly fine.
}
}
Things work fine and I’m able to execute all mysql queries.
The thing is, I don’t want to use hard-coded password instead I want to use token, token gets generated using async await. To generate token I use below code,
Approach 1
db.js
const AWS = require("aws-sdk");
const mysql = require("mysql");
const createAuthToken = async () => {
try {
const signer = new AWS.RDS.Signer();
return await signer.getAuthToken({ // uses the IAM role access keys to create an authentication token
credentials: {
region: "region",
accessKeyId: "accessKeyId",
secretAccessKey: "secretAccessKey"
},
region: "region",
username: "username",
hostname: "host",
port: 3360
})
} catch (e) {
console.log(e)
}
}
const token = await createAuthToken();
exports.database = mysql.createPool({
host: "host",
port: 3360,
user: "user",
password: token,
connectionLimit: 10
});
Error: await is only valid in async functions and the top level bodies of modules
Apporach 2
(async function () {
const token = await createAuthToken();
exports.database = mysql.createPool({
host: "host",
port: 3360,
user: "user",
password: token,
connectionLimit: 10
});
})()
but
const db= require("../db").database ; // This is undefined
Apporach 3
exports.database= async () => {
const token = await createAuthToken(); // able to generate token but exports return async function
return mysql.createPool({
host: "host",
port: 3360,
user: "user",
password: token,
connectionLimit: 10
});
}
tried other approaches as well but none of them is working and need help.
How can I make sure const db= require("../db").database
is not undefined and it gets connection pool object using async await ?