AWS – 利用 SDK 调用 Lambda 函数
     发布在:JavaScript      浏览:8      评论:0 条评论

前景提要:需要在一个 Lambda 函数中调用另一个 Lambda 函数

封装

'use strict';
const aws = require('aws-sdk');
const invocationType = 'RequestResponse';
const logType = 'Tail';
const screenshotFunctionName = 'demo-lambda-function-dev-widget-screenshot-function';

const lambda = new aws.Lambda({region: 'ap-northeast-1'});


/**
 * @name invokeWorkerLambda
 * @description Run Lambda Function by name
 * @param {string} name Lambda function name.
 * @param {object} task Parameters to call the Lambda Function.
 * @return {Promise}
 */
const invokeWorkerLambda = function invokeWorkerLambda(name, task) {
  const params = {
    FunctionName: name,
    InvocationType: invocationType,
    LogType: logType,
    Payload: JSON.stringify(task)
  };
  return new Promise((resolve, reject) => {
    return lambda.invoke(params, function(err, data) {
      if (err) {
        return reject(err);
      } else {
        const message = data['Payload'];
        const statusCode = message.split(',')[0];
        if (statusCode.indexOf('200') !== -1) {
          return resolve(message);
        } else {
          return reject(message);
        }
      }
    });
  });
};

使用

const invokeLambdaFunctions = {
  /**
   * @name runScreenshotFunction
   * @description Run lambda function about screenshot.
   * @param {Object} event
   * {
   *    url: 'http://www.baidu.com/index.html',
   *    baseline: true,
   *    env: 'dev',
   *    device: 'Desktop 1920*1080',
   *    user: '',
   *    password: ''
   * }
   * @return {Promise}
   */
  runScreenshotFunction: function runScreenshotFunction(event) {
    return new Promise((resolve, reject) => {
      return exports
          .invoke(screenshotFunctionName, event)
          .then((result) => {
            console.log('invoke screenshot', result);
            return resolve(result);
          })
          .catch((err) => {
            console.log('invoke screenshot');
            return reject(err);
          });
    });
  }
};

module.exports.invoke = invokeWorkerLambda;
module.exports.invokeLambdaFunctions = invokeLambdaFunctions;
Responses