I am using Typescript, Nodejs and sam-beta-cdk to develop a serverless application infrastructure. I would like to share utility functions between my lambdas so I don't have to write the same code over and over again.
File structure looks something like this:
lambdas > feature > lambda-name > lambda.js
layers > layer-name > nodejs > utils.js
This works very well in aws environment, however, not sure how to integrate Lambda Layers into my local development workflow.
How can I import the utilities from the layer so that it works both in aws as well as my local env?
Update the compilerOptions in the tsconfig.json of the lambda, add baseUrl and Paths :
"baseUrl": ".",
"paths": {
"/opt/nodejs/*": [
"RelativePathToUtilModule/*",
"RelativePathToAdditionalCustomLayers/*"
]
}
The lambda code can then use the exported members of util/other custom layers which will work for both locally and when deployed to AWS
import * as layer1 from "/opt/nodejs/Util";
import * as layer2 from "/opt/nodejs/SomeOtherUtility";
Since you will be uploading the layer as a Zip to create the layer during deployment, the best method is to have a step in your pipeline that creates these zips from the appropriate directory in your repo. This can easily be done with makefile util run during a codebuild.
utilities_layer
mkdir node_modules
cp -R utilities node_modules
zip -r utilities-layer.zip node_modules
(clean up if you want to here)
Then, in your lambdas you can reference that directory as part of your import statements.
Then for instance you have this structure:
|
|-utilities
|-aws
|-s3.js
|-api
|-myLambda
|-index.js
|-myLambdaUtil.js
Then in your code you would do something like
import s3 from utilities.aws
import myLambdaUtil
Note that, assuming your lambdas each have their own directory and you are referencing that directory in your deployment solution (CDK, SAM, Cloudformation templates) then the file that are in the same directory do not include the base root directory but your utilities do.
This strategy allow you to reference your utilities directory locally with ease, and keeps a similar import pattern as needed for the local env inside the lambda once deployed.
Please note: Ive been working in Python for the last year and barely touched Node, my node syntax may be a bit rusty but the general idea is the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With