gpt4 book ai didi

node.js - 在 Node js中访问谷歌云 secret 管理器数据以进行数据库连接

转载 作者:太空宇宙 更新时间:2023-11-04 01:17:27 24 4
gpt4 key购买 nike

我们有一个nodejs应用程序,其中我们的基本要求是不使用config.json文件中的硬编码数据库密码,而是从Google Cloud Secret Manager读取它,并且我我能够从那里获取该 secret 值。

但是当我尝试通过异步函数在我的models/index.js中使用它时,我收到了Promise {pending}错误。

这是我的 secret_manager.js 文件:

let _ = require('lodash');

// Imports the Secret Manager library
const { SecretManagerServiceClient } = require('@google-cloud/secret-manager');
let getSecret = async function (secretName) {

try {

if (!secretName) {
throw new TypeError('secretName argument is required to getSecret()');
}

if (typeof secretName !== 'string') {
throw new TypeError('secretName must be a string to getSecret()');
}

// Instantiates a client
console.info('Creating a SecretManagerServiceClient')
const client = new SecretManagerServiceClient();

console.info('Calling a accessSecretVersion')
const [version] = await client.accessSecretVersion({
name: secretName,
});

// Extract the payload as a string.
const payload = version.payload.data.toString('utf8');

if (_.isNil(payload) || _.isEmpty(payload)) {
let error = new Error()
error.name = 'SecretAccessError';
error.message = 'Invalid Secret Value for ' + secretName;
console.error(error);
throw error;
}
console.log("++payload=>")
console.log(payload)
return { Payload: payload }

} catch (error) {
error.name = "SecretAccessError"
console.error(error)
throw error;
}
}
module.exports = {
getSecret: getSecret
}

下面是我在index.js文件中的代码:

const secret = require('../secret_manager');

// The name of the secret
const secretName = 'my secret location in GoogleCloud'
let secretPassword;

let getSecret = async function(secretName)
{
let result = await secret.getSecret(secretName);
return result.Payload;
}

if(env=='development'){
secretPassword = getSecret(secretName);
}else{
secretPassword = getSecret(secretName);
}
console.log("secret passwprd is:")
console.log(secretPassword)

当我启动服务器时,这是我的输出:

[nodemon] starting `node start.js`
Creating a SecretManagerServiceClient
Calling a accessSecretVersion
secret passwprd is:
Promise { <pending> }
Running a GraphQL API server at http://localhost:4000/graphql in development environment!
++payload=>
**MYSECRETPASSWORD**

我如何在index.js中使用我的 secret 管理器值来进行sequelize数据库连接

最佳答案

我为我的 secret 密码添加了一个 then block ,例如:

    secretPassword.then(function (res) {
-----Rest of the logic inside this---
}

module.exports = db;

这对我有用

关于node.js - 在 Node js中访问谷歌云 secret 管理器数据以进行数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60432836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com