Ebi
Ebi

Reputation: 384

How to prevent code duplication in lambda?

I have some Nodejs functions which contain duplicated code blocks. I know that we can use lambda layer for shared libraries but i wanted to know that, is it possible to share codes too? for example one of duplicated code is shown below

const connection = mysql.createPool({
  host: process.env.DB_HOST,
  database: process.env.DB_NAME,
  user: process.env.DB_USER,
  port: process.env.DB_PORT,
  password: process.env.DB_PASSWORD
});

i want to import this block into multiple functions without writing it over and over

Upvotes: 2

Views: 1100

Answers (2)

Branson Smith
Branson Smith

Reputation: 482

One option is to create a separate Lambda with all of the shared code. Then you can invoke the shared Lambda from within all the other lambdas, or use a "Main" lambda to handle the back/forth.

Upvotes: 2

xpa1492
xpa1492

Reputation: 1973

In addition to using layers (which is probably an overkill for sharing code only), you also have two other routers you can take:

  • you can put the shared code in a separate file (so you end up with say 3 files in your project - lambda1.js, lambda2,js and shared.js). You will then need to package your lambda1 as a zip file containing lambda1.js and shared.js for example.
  • you could keep all the code in a single file (say alllambda.js) and have different handler functions configured (exports.handler1, exports.handler2) - when you configure your AWS Lambda functions, Lambda1 has Handler configured as handler1 and Lambda2 has handler2. This obviously does not scale well (and has the extra downside of sharing the initialization code).

Upvotes: 2

Related Questions