Search code examples
javascriptnode.jsamazon-web-servicesecmascript-6aws-lambda

How to call javascript class handler function in aws lambda


I am trying to use AWS lambda together with ECMA6 classes in nodejs. Currently my code looks like this (simplified version of what I really want to do):

class testClass {
    constructor(str) {
        this.str = str;
    }

    async handler(event) {
        return {
            statusCode: 200,
            body: this.str,
        };    
    }
}

module.exports = new testClass('test');

When test this locally with

const testClass = require('./testClass');
const result = await testClass.handler();

It works as expected, but when I add this to a lambda function and call it, it returns

{
  "errorMessage": "Cannot read property 'str' of undefined",
  "errorType": "TypeError",
  "stackTrace": [
    "handler (/var/task/index.js:9:24)"
  ]
}

So it seems, that the constructor of the class is not called in the lambda context. Any idea, why this is the case and how to get around this issue ?


Solution

  • You can use static function inside a es6 class, AWS expect a function with a callback param which will be executed. with the response, if you pass a class method, without instantiate the class, it will not work, that's why you should use static functions, this way:

    // MyAwesomeClassLambda.js
    
    class MyAwesomeClassLambda {
        static async myAwesomeClassFunction(event) {
            // return await someAsyncMethodLikeDataBaseCallOrSomethingLikeThat()
            return { message: 'hello world' }
        }
    }
    
    module.exports = MyAwesomeClassLambda
    

    btw the function must be async, which is the equivalent behavior to the callback that is passed in the function version

    In the AWS Lambda console, you must specify the function as: file_name.function_name, in this case MyAwesomeClassLambda.myAwesomeClassFunction