Can we use ES6 class syntax in AWS Lambda?

I would like to use ES6 class syntax in AWS Lambda using Node 6.10, but I cannot get it to work:

class widget {
    constructor(event, context, callback) {
        callback(null, `all seems well!`);
    }
}

// module.exports.handler = widget; // "Process exited before completing request"
module.exports.handler = new widget(); // "callback is not a function"

      

Has anyone had any success using the class syntax? The class constructor is not considered a handler function.

+3


source to share


2 answers


You are not following the API that Lambda expects. As the documentation says , it expects

exports.myHandler = function(event, context, callback) {};

      

which it will then call with



const handlers = require('your-module');
handlers();

      

The problem is that ES6 classes need to be instantiated with new

. Since the Lambda API says it expects a function, it expects a calling function, not a constructive function. If you want to use a class, you will need to export a function, eg.

class widget {
  constructor(event, context, callback) {
    callback(null, `all seems well!`);
  }
}

exports.myHandler = function(event, context, callback) {
    new widget(event, context, callback);
};

      

+5


source


To answer your question, yes, you can use ES6 classes with Node 6 lambda functions. But this code won't work.

The lambda handler won't be called new

in your class, so your constructor won't fire if you just pass

module.exports.handler = widget;

      



It is called widget(event, context, callback)

. If you call new

before passing it in, you have not yet received a callback reference from the handler. You are essentially creating a new object with no initialized values. You call new widget()

, but you pass nothing, and then you pass this new instance to invoke the handler.

There is no reason on earth (as far as I can tell) to do this, but you could:

class widget extends Function {
    constructor(){
      super('...args', 'return this.__call__(...args)');
      return this.bind(this);    
    }

    __call__(event, context, callback) {
     callback(null, "Dude, this is wierd.")
   }
}
exports.handler = new widget()

      

0


source







All Articles