【问题标题】:AWS Lambda Node.js Object BindingAWS Lambda Node.js 对象绑定
【发布时间】:2021-03-17 23:50:43
【问题描述】:

我正在编写一个 JavaScript / Node.js AWS Lambda 函数,其中包含来自不同事件源(例如 SQS 和 APIGateway)的触发器。应用程序的入口点是 index.js 文件。处理程序将根据来自事件源的上下文,将执行委托给相应的处理程序。

当我运行单元测试时,Handler.create 函数按预期调用 Handler 原型上的 getHandler 方法,但当我将代码部署到 AWS Lambda 时,情况并非如此。 Handler.create 函数按预期调用,但“this”绑定到 AWS Lambda 客户端/运行时对象。由于 Client 对象没有 getHandler 方法,因此调用不存在的函数时出现错误。

入口点

处理程序: index.create

文件:./index.js

const Handler = require('./Handler');

// Singleton
let handler;
const getHandler = () => {
  if (handler === undefined) {
    handler = new Handler();
  }
  return handler;
}

module.exports = getHandler();

处理逻辑

文件:./Handler.js

const Handler = function() {
}

Handler.prototype.create = function(event, context) {
  // Expect: "this" to be the instance of handler.
  // Actual: "this" is the AWS Lambda Client / Runtime object
  const handler = this.getHandler(event, context);
  // Error - this.getHandler is not a function
  return handler.create(event, context)
}

Handler.prototype.getHandler = function(event, context) {
  if (this.isEventAPIGateway(event, context))
    return new APIGatewayHandler();
  if (this.isEventSQS)
    return new SQSHandler();
  ...
  throw new Error('Unsupported Event Source')
}


【问题讨论】:

    标签: javascript amazon-web-services lambda


    【解决方案1】:

    在放弃尝试解决问题后,我找到了以下解决方法。在 index.js 文件中,我创建了一个新对象并将函数绑定到处理程序。

    let handler;
    const getHandler = () => {
      if (handler === undefined) {
        handler = new Handler();
      }
      return {
        create: (...args) => handler.create.apply(handler, args)
      };
    }
    
    module.exports = getHandler();
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      • 2021-09-19
      • 2021-07-17
      • 2018-11-20
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多