Refactor Lambda & Automate Deployments: Handler.js To Media.js
Hey guys! Today, we're diving into a project focused on cleaning up our codebase and making our lives easier with automation. Specifically, we're renaming a file for clarity and setting up automatic deployments using GitHub Actions. Let's get started!
Description
The main goal here is to rename handler.js to media.js. Why? Because media.js better describes what this file actually does: act as a media upload proxy. Think of it like giving your code files more descriptive names so everyone (including future you!) knows what's going on at a glance. We're also adding automatic deployment to GitHub Actions so that we don't have to manually deploy the code.
Changes
To achieve these goals, we'll be making several key changes:
- Renaming the File: We're renaming
infra/lambda/handler.jstoinfra/lambda/media.js. This is the core of the change. - Updating the SAM Template: We need to explicitly tell our SAM (Serverless Application Model) template that our handler is now
media.handler. SAM uses this to know which function to execute when our Lambda is triggered. - Updating
package.json: Themainfield inpackage.jsontells Node.js where the entry point of our application is. We need to update it to reflect the new file name. - Updating
README.md: OurREADME.mdfile is the go-to guide for anyone working on the project. We need to update any references tohandler.jsin the README tomedia.js. - Adding GitHub Actions Workflow: This is where the automation magic happens! We'll add a workflow to our GitHub Actions configuration that automatically packages and deploys our
media.jsfile whenever we push changes to our repository. - Updating Test Files: If any of our test files reference
handler.js, we need to update those references tomedia.jsas well.
Acceptance Criteria
How do we know if we've succeeded? We need to meet the following criteria:
- [ ] The file is renamed from
handler.jstomedia.js. - [ ] The SAM template is updated with the explicit handler.
- [ ] The
package.jsonmainfield is updated. - [ ] The
README.mdreferences are updated. - [ ] The GitHub Actions workflow is updated to package and deploy
media.js. - [ ] All tests pass.
- [ ] AWS console instructions are provided for manual handler update (just in case!).
Detailed Explanation of Changes and Acceptance Criteria
Let's break down each change and acceptance criterion in more detail:
1. Renaming the File: infra/lambda/handler.js to infra/lambda/media.js
This is the most straightforward change. We're simply renaming the file. The importance here lies in the semantic clarity it provides. Instead of a generic handler.js, we now have media.js, which immediately tells anyone browsing the codebase that this file deals with media uploads. This small change significantly improves code maintainability and understandability. It helps new developers (or even yourself, months down the line) quickly grasp the purpose of the file without having to dig through the code.
Acceptance Criterion: Verify that the file has indeed been renamed in the repository. You can check this through your Git client, your IDE, or directly on GitHub.
2. Updating the SAM Template
The SAM template (usually template.yaml or template.yml) defines our serverless application. It tells AWS how to deploy our Lambda function, what triggers it, and what permissions it needs. The Handler property within the UploadProxyFunction definition specifies which function within our code should be executed when the Lambda is invoked. Before the change, it likely pointed to handler.handler. Now, it must point to media.handler.
Resources:
UploadProxyFunction:
Type: AWS::Serverless::Function
Properties:
Handler: media.handler
# Other properties...
Why is this important? If we don't update the SAM template, AWS will still try to execute the old handler.handler function, which no longer exists! This will result in errors and our media upload proxy will fail.
Acceptance Criterion: Inspect the SAM template file and confirm that the Handler property for the UploadProxyFunction is explicitly set to media.handler.
3. Updating package.json
The package.json file is the heart of any Node.js project. It contains metadata about the project, including dependencies, scripts, and the entry point of the application. The main field specifies the module that should be loaded when the package is required. In our case, it likely pointed to handler.js. We need to update it to media.js.
{
"name": "your-project-name",
"version": "1.0.0",
"description": "",
"main": "media.js",
# Other properties...
}
Why is this important? While not strictly required for Lambda functions (as the handler is explicitly defined in the SAM template), updating package.json is good practice. It ensures that if the package were to be used in other contexts (e.g., required by another Node.js application), the correct entry point would be used.
Acceptance Criterion: Open the package.json file and verify that the main field is set to media.js.
4. Updating README.md References
The README.md file is the first thing developers see when they look at our project. It should provide clear instructions on how to set up, run, and deploy the application. If the README.md contains any references to handler.js (e.g., in code examples, deployment instructions, or explanations of the architecture), we need to update those references to media.js.
Why is this important? Outdated documentation can lead to confusion and errors. Keeping the README.md up-to-date ensures that developers have accurate information and can easily contribute to the project.
Acceptance Criterion: Carefully review the README.md file and replace all instances of handler.js with media.js. Use a text editor's find and replace functionality to ensure you catch every occurrence.
5. Adding GitHub Actions Workflow
This is where we automate the deployment process! GitHub Actions allows us to define workflows that automatically run when certain events occur in our repository (e.g., a push to the main branch). We'll create a workflow that packages our Lambda function and deploys it to AWS.
A typical GitHub Actions workflow for a SAM application might look like this:
name: Deploy to AWS
on:
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: '3.x'
- name: Install dependencies
run: pip install aws-sam-cli
- name: Build
run: sam build
- name: Deploy
run: sam deploy --guided --no-prompts
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
AWS_REGION: your-aws-region # e.g., us-east-1
Key Considerations:
- Secrets: Store your AWS access key ID and secret access key as secrets in your GitHub repository settings. Never commit these credentials directly to your code!
sam deploy --guided: The--guidedflag will prompt you for configuration options the first time you run the deployment. After that, you can use--no-promptsto automate subsequent deployments.AWS_REGION: Make sure to set theAWS_REGIONenvironment variable to the correct AWS region where you want to deploy your Lambda function.
Acceptance Criterion:
- Verify that the GitHub Actions workflow file exists in your repository (usually in
.github/workflows). - Confirm that the workflow is triggered on pushes to the
mainbranch (or whichever branch you're using for deployment). - Ensure that the workflow includes steps to build and deploy the SAM application.
- Most importantly, trigger the workflow by pushing a change to your repository and verify that the deployment succeeds in the GitHub Actions console.
6. All Tests Pass
Before and after any code changes, it's crucial to run your tests to ensure that everything is working as expected. This includes unit tests, integration tests, and end-to-end tests.
Why is this important? Tests help us catch bugs early and prevent regressions (i.e., introducing new bugs while fixing old ones). Running tests after renaming handler.js ensures that the change didn't break any existing functionality.
Acceptance Criterion: Run all your tests and verify that they pass. If any tests fail, investigate the cause and fix the code or the tests as needed.
7. AWS Console Instructions for Manual Handler Update
In rare cases, automatic deployment might fail or you might need to update the handler manually through the AWS console. Providing clear instructions for this process is a good safety net.
Instructions:
- Log in to the AWS Management Console.
- Navigate to the Lambda service.
- Select your Lambda function (UploadProxyFunction).
- Click on the "Configuration" tab.
- Click on "General configuration" then āEditā.
- In the "Runtime settings" section, edit the "Handler" field from
handler.handlertomedia.handler. - Click "Save".
Acceptance Criterion: Document these instructions in a clear and concise manner, either in the README.md file or in a separate document.
Related
This change prepares the ground for implementing restaurant tracking functionality by making the handler naming more semantic. A clear and well-organized codebase makes it easier to add new features and maintain existing ones. By renaming handler.js to media.js, we're taking a small but important step towards a more maintainable and scalable application.
So, there you have it! By following these steps, we've not only cleaned up our code but also automated our deployment process, making our lives as developers a whole lot easier. Keep coding, guys!