简体   繁体   English

AWS Lambda Node.js Object 绑定

[英]AWS Lambda Node.js Object Binding

I am writing a JavaScript / Node.js AWS Lambda function with triggers from different event sources (eg SQS and APIGateway).我正在写一个 JavaScript / Node.js AWS Lambda ZC1C425268E68385D1AB5074C17A94FQS4G 和不同事件源的 API(例如 SAFQS4G 触发)。 The entry point for the application is the index.js file.应用程序的入口点是 index.js 文件。 The Handler will, based on context from the event source, delegate the execution to respective handlers.处理程序将根据来自事件源的上下文,将执行委托给相应的处理程序。

When I run my unit test the Handler.create function calls the getHandler method on the Handler prototype as expected, but this is not the case when i deploy the code to AWS Lambda.当我运行单元测试时,Handler.create function 按预期调用 Handler 原型上的 getHandler 方法,但是当我将代码部署到 AWS Lambda 时,情况并非如此。 The Handler.create function is called as expected, but "this" is bound to the AWS Lambda Client / Runtime object. Handler.create function 按预期调用,但“this”绑定到 AWS Lambda 客户端/运行时 object。 As the Client object does not have a getHandler method, I get an Error for calling a function that does not exist.由于客户端 object 没有 getHandler 方法,因此调用不存在的 function 时出现错误。

Entry Point入口点

handler: index.create处理程序: index.create

File: ./index.js文件: ./index.js

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

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

module.exports = getHandler();

Handler logic处理程序逻辑

File: ./Handler.js文件: ./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')
}


After giving up trying to solve the problem, I found the following workaround.在放弃尝试解决问题后,我找到了以下解决方法。 In the index.js file I created a new object and bound the function to the handler.在 index.js 文件中,我创建了一个新的 object 并将 function 绑定到处理程序。

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

module.exports = getHandler();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM