amazon-web-servicesaws-lambdaaws-api-gatewayaws-http-api

Export methods to use in other file in same lambda function- Node.js


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?


Solution

  • 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.