Learning to make use of AWS Lambda function: Cron Jobs (plus Pub-Sub pattern)

import "source-map-support/register";import config from "./app/config";import app from "./app";import cron from "node-cron";import { sendMonthlyReport } from "./app/jobs";if (config.app.env === "production") {cron.schedule("0 10 28 * *", sendMonthlyReport); // run at 28th day every month}app.listen(config.app.port, () => console.log(`App listening on port ${config.app.port}`));
// handler.ts
import "source-map-support/register";
import { sendMonthlyReport } from "./functions"
export const send_monthly_report = sendMonthlyReport
// sendMonthlyReport.ts
export const sendMonthlyReports: APIGatewayProxyHandler = async (_, context) => {
try {
// query invested users
// loop through each user
// generate pdf report
// send email to each user with attached file
return { statusCode: 200, body: JSON.stringify({ message: "Success" })
};
...
// serverless.ymlFunctions:
send_monthly_reports:
handler: handler.send_monthly_reports
events:
- schedule:
name: ${self:custom.stage}-send-monthly-reports
rate: cron(0 3 1 * ? *) # vn time 10AM 1st month
  • Query users who invested in the month & get trading data
  • Loop through each user: Generate pdf report with headless Chrome & Send email with Sendgrid
  • Query users who invested in the month & get trading data
  • Loop through each user: send necessary data as a message to a SNS topic (i.e. 1 message for 1 user)
  • Another Lambda function will subscribe to that topic then consume the message to carry out task
// sendMonthlyReport.ts
export const sendMonthlyReports: APIGatewayProxyHandler = async (_, context) => {
try {
const userIds = await getInvestedUserIds();
for (const userId of userIds) {
await publishSNS({userId}, "SendUserReportTopic")
}
...// subscriberReport.ts
export const subscriberReport: SNSHandler = async (event, context) => {
let fileName = "monthlyWealthReport";try {logger(`[SNS] Message received: ${event.Records[0].Sns.MessageId}`);const message: { userId: string } = event.Records[0].Sns.Message && JSON.parse(event.Records[0].Sns.Message); // logic to generate report, upload to S3, send email, etc....// serverless.ymlFunctions:
send_monthly_reports:
handler: handler.send_monthly_reports
events:
- schedule:
name: ${self:custom.stage}-send-monthly-reports
rate: cron(0 3 1 * ? *) # vn time 10AM 1st month
sub_send_monthly_report_by_user_id:
handler: handler.sub_send_monthly_report_by_user_id # send wealth report for user - Subscriber
events:
- sns: ${self:custom.stage}-SendEmailWealthReport

--

--

--

From translator -> Manual QC Engineer -> Automation QA Engineer -> NodeJS Developer -> yearning to learn more

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

AWS EFS- Elastic File System

Thoughts About My OSS

Writing CSV Files from other Files — For Data Science purpose.

Setup Git on WP Engine

OOP: Why use objects?

Using Coroutines in Unity

How to Pass the Machine Design and Materials PE Exam

Github Copilot, the AI we don’t want

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Hung Tran Nguyen

Hung Tran Nguyen

From translator -> Manual QC Engineer -> Automation QA Engineer -> NodeJS Developer -> yearning to learn more

More from Medium

What exactly is a REST / RESTful API?

How detect slow SQL query in PostgreSQL with EXPLAIN command

When to Use NoSQL and MongoDB

Deploying web application on CI/CD Pipeline using Heroku and GitHub Actions