Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

489
Visualizações
JavaScript, ¿cómo ejecutar un fragmento de código solo una vez?

Estoy guardando mi contenido .env dinámicamente desde el administrador de secretos de AWS, pero quiero guardar todos los valores solo una vez que se inicia el servidor. ¿Cuál debería ser el enfoque?

estoy usando mecanografiado:

 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` ); } }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Podría usar un valor booleano para recordar si el código se ejecutó o no. Algo como esto:

 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`); } } }); }
about 4 years ago · Juan Pablo Isaza Relatório

0

Estoy guardando mi contenido .env dinámicamente desde el administrador de secretos de AWS.

¿Por qué quieres guardarlos en .env ? Puede guardarlos en el objeto de configuración y puede reutilizarlos donde los necesite.

 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;

En tus archivos puedes usar esto:

 const SecretsManager = require('./SecretsManager.js'); const secret = SecretsManager.getSecretValues();

Puedes consultar aquí para más detalles.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda