Importing Local Project Logic in Multiple Lambdas in SAM Serverless TypeScript Application

0

I am having a challenge of importing local functions into my lambdas in my SAM serverless project. The "aws-lambda" dependency is working well but my own logic files won't get to the aws lambda as when I deploy the lambda and try running it, it has a "module not found" error in the API Gateway test. I thought it was possible to run a serverless stack with multiple API Gateways and Lambdas and Dynamo Tables with a shared codebase where lambdas can pull functionality from the shared local codebase. Some resources online either say that I should not import local libraries into my lambdas and if I do to use layers which I thought I didnt need to do.

The structure of my project is the following:

project-name

-src

----src/helpers

----src/lib

----src/var

----src/create-user.ts (my lambda)

----src/get-user.ts (another lambda for example)

-package.json

-template.yaml (for SAM)

-ts.config.json

I want to ensure that my create-user.ts lambda and get-user.ts lambda can get access the functions within src/helpers, src/lib, src/var... Below is the code example for create-user.ts lambda.

import {APIGatewayProxyEvent} from "aws-lambda";
import {validateCreateUserRequest} from "../src/lib/requestValidators/apiGatewayValidator";
import {createAndStoreUserLogic} from "../src/lib/logic/users/createAndStoreUserLogic";

export const handler = async (event: APIGatewayProxyEvent): Promise<void> => {
    // Log the event argument for debugging and for use in local development.
    console.log(JSON.stringify(event, undefined, 2));

    try {
        validateCreateUserRequest(event);
        await createAndStoreUserLogic(<string>event.body);
    } catch (e) {
        console.error("Error creating user");
        throw e;
    }
};
1 réponse
0

Worked with quickstart template "7 - Serverless API" from "sam init" and observed that the template needs to be specified with absolute path while specifying handlers as below to get all the files to the Lambda environment

getByIdFunction: Type: AWS::Serverless::Function Properties: Handler: src/handlers/get-by-id.getByIdHandler Runtime: nodejs18.x Architectures: - x86_64

Feel free to reach out on the support case with any further concerns and we will be happy to review template and architecture to the best of our knowledge.

AWS
INGÉNIEUR EN ASSISTANCE TECHNIQUE
répondu il y a 6 mois

Vous n'êtes pas connecté. Se connecter pour publier une réponse.

Une bonne réponse répond clairement à la question, contient des commentaires constructifs et encourage le développement professionnel de la personne qui pose la question.

Instructions pour répondre aux questions