[英]JavaScript, how to run a piece of code only once?
我正在从 AWS 机密管理器动态保存我的.env
内容,但我想在服务器启动后保存所有值。 应该采取什么方法?
我正在使用打字稿:
getSecrets("key").then((keys: any) => {
const originalKeys = JSON.parse(keys);
for (const key in originalKeys) {
if (originalKeys.hasOwnProperty(key)) {
appendFileSync(
__dirname + "/.env",
`${key}='${originalKeys[key]}'\n`
);
}
}
您可以使用布尔值来记住代码是否已执行。 像这样的东西:
let excecuted = false;
if (!excecuted) {
excecuted = true;
getSecrets("key").then((keys: any) => {
const originalKeys = JSON.parse(keys);
for (const key in originalKeys) {
if (originalKeys.hasOwnProperty(key)) {
appendFileSync(__dirname + "/.env", `${key}='${originalKeys[key]}'\n`);
}
}
});
}
我正在从 AWS 机密管理器中动态保存我的 .env 内容。
为什么要将它们保存在.env
中? 您可以将它们保存在配置对象中,并且可以在需要它们的任何地方重复使用它们。
const AWS = require('aws-sdk');
class SecretsManager {
let #config = null;
async #getSecret (secretName, region){
const config = { region : region }
var secret, decodedBinarySecret;
let secretsManager = new AWS.SecretsManager(config);
try {
let secretValue = await secretsManager.getSecretValue({SecretId: secretName}).promise();
if ('SecretString' in secretValue) {
return secret = secretValue.SecretString;
} else {
let buff = new Buffer(secretValue.SecretBinary, 'base64');
return decodedBinarySecret = buff.toString('ascii');
}
} catch (err) {
if (err.code === 'DecryptionFailureException')
// Secrets Manager can't decrypt the protected secret text using the provided KMS key.
// Deal with the exception here, and/or rethrow at your discretion.
throw err;
else if (err.code === 'InternalServiceErrorException')
// An error occurred on the server side.
// Deal with the exception here, and/or rethrow at your discretion.
throw err;
else if (err.code === 'InvalidParameterException')
// You provided an invalid value for a parameter.
// Deal with the exception here, and/or rethrow at your discretion.
throw err;
else if (err.code === 'InvalidRequestException')
// You provided a parameter value that is not valid for the current state of the resource.
// Deal with the exception here, and/or rethrow at your discretion.
throw err;
else if (err.code === 'ResourceNotFoundException')
// We can't find the resource that you asked for.
// Deal with the exception here, and/or rethrow at your discretion.
throw err;
}
}
static async getSecretValues() {
const secretName = '<secretsName>';
const region = '<Region>';
try {
if (!this.#config) {
return this.#config;
} else {
this.#config = await this.#getSecret(secretName, region);
}
} catch (e) {
console.log(e);
}
}
}
module.exports = SecretsManager;
在您的文件中,您可以使用它:
const SecretsManager = require('./SecretsManager.js');
const secret = SecretsManager.getSecretValues();
您可以在此处查看更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.