How to handle Typescript lambdas using modules embedded in a CDK project

0

I have a question that's kind of a CloudFormation question but I guess is really a CDK question. My project layout looks like this:

work\.
├───cdk.out
├───bin
├───lib
├───node_modules
├───src
│   ├───common
│   ├───ep
│   ├───sites
│   └───static
├───package.json
├───tsconfig.json
└───test

The directories ep, sites, and static are all individual lambdas; the constructor script calls them out like this:

entry: path.join(__dirname, "../src/sites/sites.ts"),

so that works great. In the package.json I am very careful about what goes into 'dependencies' vs. 'devDependencies' to avoid conflicts and bloat.

It occurred to me, though, that some day I might end up with other problems, like conflicts, so I was searching around to see if I can give each individual lambda (ep, sites, static) their own package.json and maybe even tsconfig.json. I found a few things saying it works, but a few others saying it won't. yarn build only shows it running tsc once. I think the answer to this is to use modules but because of the way you define an entry point (as a path to a single file) I don't get the idea this would work.

I'm not sure how to make the lambdas within the CDK project more independent. Do I need to build them into their own, separate projects (outside of the CDK project), bundle them (say with webpack), then have the CDK project reference the build outputs for each? That sounds a little messier, and I like having the entire stack (lambdas and all) in one place. Is there a more self-contained way to do this?

Generally speaking, my lambdas are classes. This means that each one has an entry point defined that's just a regular function. If I knew how modules work, could I make each lambda be a module, that's its own class, and have 'entry' point to just a plain typescript function that's part of the CDK project that does something like:

import { SpecialHandler } from ../xyz;

export async function handleSpecialRequest(request: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> {
    return new SpecialHandler.handleRequest(request);
}
profile picture
wz2b
已提问 1 年前281 查看次数
1 回答
0
已接受的回答

Hi there! I've seen others tackle this problem with tooling like Learn (https://lerna.js.org/). However, I would be wary of going the monorepo direction as the CDK team has baked in a lot of tooling around packaging and deploying JS/TS lambda's. If you were to go this route you would be reinventing the wheel, I could only recommend it if the problem is prevalent and not just a hammer in search of a nail.

已回答 1 年前
profile picture
专家
已审核 1 个月前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则