0

In my lambda using http api gateway with reverse proxy integrated, I need to check for different routes for the API. I have 2 index.js files for now, in the main file, I have the handler:

...
const read_all_Todos = require("./lib/read_all/index");

const main = (event, context, callback) => {

    let httpMethodCall = event.requestContext.http.method;
    let itsCallingFrom = event.rawPath;

    switch (itsCallingFrom) {
        case '/v1/listalltodos':
            read_all_Todos.test(event, context, callback);
            break;
        default:
            return callback(null, { method: httpMethodCall, rawPath: itsCallingFrom });
    }
};

...

on the other file I have:

export function test(event, context, callback) {
    let httpMethodCall = event.requestContext.http.method;
    let itsCallingFrom = event.rawPath;
    
    return callback(null, { method: httpMethodCall, rawPath: itsCallingFrom });
}

when a user goes to the url /v1/listalltodos I see message "Internal Server Error"

What's wrong here?

EDIT:

Every time I try to export a function on the logs I see this: "errorMessage": "SyntaxError: Unexpected token 'export'",

so what is the correct way to export methods in lambda?

ElKePoN
  • 822
  • 11
  • 21

1 Answers1

1

Well I figured it out, it was giving internal server error because it doesn't use the common JavaScript practice of export, this is how it has to be done:

1- You import your file as usual:

const read_all_todos = require("./lib/read_all/ReadAllTodos");

2- You call it in that same file: read_all_todos.foo();

3- This is the key/different part, you define the export like this

function internal_foo () {
    console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
    return 1;
}

module.exports.foo = internal_foo;

As you can see, you have to export it as a module, if you only write export ... it will throw an internal server error.

Dharman
  • 30,962
  • 25
  • 85
  • 135
ElKePoN
  • 822
  • 11
  • 21
  • I'm having this same issue. This is the common JS method. However, [from AWS Docs](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html), it shows a code example with ES Module export feature in use. What am I missing that prevents export keyword from being used? – Alex Apr 01 '23 at 23:48