【发布时间】: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