Lambda Utility Methods
Explore how to design robust AWS Lambda applications by creating reusable utility methods for JSON responses and error handling. Understand how to manually test Lambda entry points and implement throttling at both API Gateway and Lambda levels to safeguard your serverless functions from abuse and control costs. Learn techniques to monitor throttling events and ensure your app scales securely and efficiently.
We'll cover the following...
You have already used json-response.js to format JSON objects into something that Lambda can understand, but this method loaded the CORS origin from the process environment, which should be the responsibility of the Lambda entry point. You can remove the process variable and add it as another regular argument, which makes this method easy to test.
When only the Lambda entry point depends on the actual Lambda infrastructure, you can cover utility methods with focused in-memory tests. The next listing shows what a test for the jsonResponse function would look like using jest (again, for simplicity, only the basic test cases are included, but in a real project you would include many more boundary scenarios).
You’ll need another utility method to report errors back. JavaScript is specific regarding error handling, because it can pass around exceptions or strings or just plain objects as errors, so you need to ensure that all the options are converted into a string. You’ll also pass a generic HTTP error code 500 back, instead of the 200 which signals success. A file called error-response.js is created in the user-form Lambda directory, with the following code.
The test cases for errorResponse would look similar to the tests for jsonResponse, so they will be omitted from this course. You can write them for homework.
Lambda entry code
The main Lambda file now just needs to connect all the dots. It should load the configuration from environment variables, parse events and variables ...