使用Node.js构造对象异步

时间:2017-01-31 14:29:41

标签: node.js

我正在尝试使用AWS密钥管理服务(KMS)从AWS Lambda函数解密一些环境变量,然后使用解密的凭据发布推文。但是,在使用Twitter对象之前,环境变量没有被解密。这导致身份验证失败。

在调用其成员函数之前,如何确保下面代码中的Twitter对象完全实例化/初始化?我应该使用promises吗?

var AWS = require('aws-sdk');
var Twitter = require('twitter');
var s3 = new AWS.S3();
var kms = new AWS.KMS();

function DecryptEnvironmentVariable(creds, varname) {
    console.log(`Decrypting environment variable named ${varname}`);
    console.log(process.env[varname]);

    params = {
        CiphertextBlob: process.env[varname]
    }
    kms.decrypt(params, function (err, data) {
        if (err) {
            console.log(err);
        }
        else {
            console.log("Successfully decrypted envrionment variable.");
            return data.Plaintext;
        }
    });
}

exports.tweet = function (event, context) {
    // Instantiate the Twitter object
    var twitterclient = new Twitter({
        consumer_key: DecryptEnvironmentVariable('TWITTER_CONSUMER_KEY'),
        consumer_secret: DecryptEnvironmentVariable('TWITTER_CONSUMER_SECRET'),
        access_token_key: DecryptEnvironmentVariable('TWITTER_ACCESS_TOKEN_KEY'),
        access_token_secret: DecryptEnvironmentVariable('TWITTER_ACCESS_TOKEN_SECRET'),
    })

    // Post a new tweet
    twitterclient.post('statuses/update', { status: "messagegoeshere" })
    .then(function(tweet) {
        console.log("Tweet was successfully posted!");
    })
    .catch(function(error) {
        console.log("Error occurred while posting tweet. :(");
        console.log(error);
    });
}

2 个答案:

答案 0 :(得分:1)

DecryptEnvironmentVariable实际上并没有返回任何内容,因此您无法以您尝试的方式使用它。

由于您需要获取多个异步操作的结果,因此最简单的方法可能是使用Promise.all(假设您正在使用当前版本的nodejs):

var AWS = require('aws-sdk');
var Twitter = require('twitter');
var s3 = new AWS.S3();
var kms = new AWS.KMS();

function DecryptEnvironmentVariable(creds, varname) {
  return new Promise(function (resolve, reject) {
    console.log(`Decrypting environment variable named ${varname}`);
    console.log(process.env[varname]);

    params = {
      CiphertextBlob: process.env[varname]
    }
    kms.decrypt(params, function (err, data) {
      if (err) {
        console.log(err);
        reject(err);
      }
      else {
        console.log("Successfully decrypted envrionment variable.");
        resolve(data.Plaintext);
      }
    });
  });
}

exports.tweet = function (event, context) {
  // Instantiate the Twitter object
  var tasks = [
    DecryptEnvironmentVariable('TWITTER_CONSUMER_KEY'),
    DecryptEnvironmentVariable('TWITTER_CONSUMER_SECRET'),
    DecryptEnvironmentVariable('TWITTER_ACCESS_TOKEN_KEY'),
    DecryptEnvironmentVariable('TWITTER_ACCESS_TOKEN_SECRET')
  ];

  return Promise.all(tasks).then(function (keys) {

    var twitterclient = new Twitter({
      consumer_key: keys[0],
      consumer_secret: keys[1],
      access_token_key: keys[2],
      access_token_secret: keys[3]
    });

    // Post a new tweet
    return twitterclient.post('statuses/update', { status: "messagegoeshere" });
  })
  .then(function(tweet) {
    console.log("Tweet was successfully posted!");
  })
  .catch(function(error) {
    console.log("Error occurred while posting tweet. :(");
    console.log(error);
  });
}

答案 1 :(得分:0)

AWS Lambda supports environment variables natively。因此,您无需使用KMS自行加密/解密它们。使用内置的环境变量可以让您更容易和同步地使用它们,只需访问它们通常位于process.env.TWITTER_CONSUMER_KEY的位置。