Node.JS AWS Lambda Project Example

Link

Recently having needed to write a lambda function in AWS, I found that there were not many existing examples of how to best structure a Node lambda project in AWS. I found that the following setup worked well for keeping things organized.

Project Structure

project-root-function-name
│   README.md
|   package.json
|   package-lock.json
│   .gitignore
|   .eslintrc.json
|
└───src
│   │   index.js
│   │   config.json
│   │
│   └───components
│       │   FooClass.js
│       │   BarClass.js
│       └───...
│   
└───test
    │   fooTest.js
    │   barTest.js
    └───...

Invoking and Deploying Function Locally

It's pretty handy to have some snippet scripts for working with the AWS environment.

Adding the following scripts to your package.json will allow you to simulate an AWS runtime

Invoking your function

...
"scripts": {
	...
    "invoke": "node -e \"require('./index').handler(null,null)\"",
    ...
  },
  ...

Of course, you can pass non-null event and context arguments to the invocation if your function requires some actual parameter.

Deploying your function

It's possibly a good idea to minify your package before deploying it to Lambda. This reduces bandwidth and deploy runtime. However, the quick and dirty way of deploying your function with the above project structure is easily accessible with the following script:

...
"scripts": {
	...
	"deploy": "zip -r function.zip .; aws lambda update-function-code --function-name <YOUR_FUNCTION_NAME> --zip-file fileb://function.zip;rm ./function.zip",    ...
  },
  ...

This function will zip up your entire project folder, so you'll possibly be including a lot of files–including the entire contents of your node_modules folder–that are not actually needed. There are plenty of strategies available for reducing your function deployment package size. This may or may not matter to your use case.

Fitting these scripts into your workflow is quite easy, as you can just run npm run invoke and npm run deploy to perform those script actions.

Conclusion

There you have it. Hopefully this will aid in the development of additional Lambda functions. Feel free to leave your thoughts.