Monday, March 9, 2020

How to share code between AWS Lambda functions using Serverless Application Model in Node.js

I'm writing this post because it turned out to be a lot more difficult that I think it should've been.
I mean, who doesn't have code that they want to share between lambda functions?
And who doesn't want to debug those functions or business logic inside of those functions quickly--that doesn't require firing up the whole lambda into the AWS environment?

We wanted to have a utility package that wraps all of the details when accessing our architecture.  We wanted the lambda functions to be as readable and minimal as possible.

I kid you not--it took three of us three to four days to figure out a reasonable solution!

Here were our requirements:
  • Be able to debug locally
  • Be able to run unit tests on business logic (without having to be ran in an AWS sandbox)
  • Be able to run tests in sam local start-api
  • Be able to debug the code in the container via sam local invoke
  • sam build works
  • sam deploy works
  • Runs in AWS Lambda in the cloud
The first idea I had was to add a file reference to the package.json file inside the lambda folders and let npm pull those dependencies in.  It worked perfectly--the first time.  The second time I did a sam build, it DELETED all of the shared code!  WHY?  Apparently, when an .aws-sam folder exists, it performs an npm cleanup of some sort and that appears to delete the shared code.  That was sad because that was a super clean implementation and I was reluctant to walk away from it.

Anyway, one of my coworkers went down another path and required dependencies using a ternary operator.  If we're running in AWS, then require the full path where the layer is installed.  Otherwise, require the relative path to the shared code.

We created a github repo to help others get an easy start, here: https://github.com/blmille1/aws-sam-layers-template.


Please refer to them for a more in-depth explanation.

Be blessed!