Q: AWS Lambda Node.js Object Binding I am writing a JavaScript / Node.js AWS Lambda function with triggers from different event sources (e.g. SQS and APIGateway). The entry point for the application is the index.js file. 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. The Handler.create function is called as expected, but "this" is bound to the AWS Lambda Client / Runtime object. As the Client object does not have a getHandler method, I get an Error for calling a function that does not exist.
Entry Point
handler: index.create
File:./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
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')
}




A: 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.
let handler;
const getHandler = () => {
  if (handler === undefined) {
    handler = new Handler();
  }
  return {
    create: (...args) => handler.create.apply(handler, args)
  };
}

module.exports = getHandler();


