asnyc function for retrieving Google Secret Manager Variable returns promise pending

Viewed 151

I am trying to switch my environment variables to Google Secrets Manager, but I am encountering a problem. I am running an expressjs api trying to establish a database connection. But whatever I try, it only returns Promise { <pending> } instead of waiting for the async function to finish. Any help is highly appreciated!

gcloud.js

const { SecretManagerServiceClient } = require('@google-cloud/secret-manager');
const client = new SecretManagerServiceClient();

async function getSecret(name) {

const name = `projects/PROJECT-ID/secrets/${name}/versions/latest`;

const [version] = await client.accessSecretVersion({
  name: name,
});

const payload = version.payload.data.toString();

return payload;
}

module.exports.getSecret = getSecret;

config.js

const gcloud = require('./config/gcloud.js')

const config = {
  authSecret: gcloud.getSecret(SECRET_NAME)
}

module.exports = config
1 Answers

You need to await the result of gcloud.getSecret:

// Not actually valid
const config = {
  authSecret: await gcloud.getSecret(SECRET_NAME)
}

However, top-level await isn't widely supported yet, so you'll need to build the config inside a function: NodeJS Async / Await - Build configuration file with API call

Related