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개 답변
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
지원 엔지니어
답변함 6달 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인