Running Twilio Serverless Functions Using Database Events
Time to read: 7 minutes
Running Twilio Serverless Functions Using Database Events
In the world of modern application development, event-driven architecture has become a popular paradigm for building scalable and responsive systems. Event-driven messaging allows developers to design applications that respond dynamically to changes in the system, ensuring a more real-time response and efficient user experience.
Imagine a scenario where you need to automatically send SMS or push notifications as soon as a task enters a ”success” or ”done” state in your application. How can you achieve this without constantly polling your database for updates? In this article, we will explore how to leverage event-driven architecture to trigger Twilio Functions based on data change in a MongoDB database.
Prerequisites
Here are what you need to follow along in this tutorial
- Node.js installed
- A free Twilio account ( sign up with Twilio for free ).
- Install Ngrok and make sure it’s authenticated.
Developing Your Application
To set up your APIs, I attached a link to a codebase that contains the base application used for this tutorial. It contains all the code necessary to start a Node.js server and some already-made endpoints that work once you connect to a MongoDB database. This section will work you through how to run the project on your local machine, set up Twilio, and any other requirements you need to build your solution
Running the Node.js API
The API we will use in this guide is a bookstore API that allows authors to upload book inventory and readers to rent or borrow to return in due time. To get the project running on our local machine, you can follow these steps:
Navigate to your terminal and clone the project from the GitHub repository by running the following command:
Make sure you are in the twilio-starter branch and then run the installation script within the project directory to install the needed packages:
Fill in the options as shown below and proceed to create your cluster. This cluster will contain all the tables and their respective data for our application. Click on Create to continue.
You will need to set access and authorization next. As shown below, MongoDB auto-generates a username and password for your cluster. Kindly update them to what you want and save them using the Create User button. Add 0.0.0.0/0to the IP Access List input and click Add Entry to save. This allows access to your MongoDB database from any IP. You can update this later from the Network Access tab in the dashboard if you want to give access to limited IPs.
Click on the Finish and Close button to finish your setup and navigate to the dashboard. From the Dashboard, we can get the link to connect to our database by clicking Connect
You will get to see different options to connect to your MongoDB database. In the tutorial, you will be using the Drivers which help you to access your data using MongoDB’s native drivers (e.g. Node.js, Go, etc.).
When you select the Drivers option, you will see the page with the credentials you need. It is a URL with a placeholder for your cluster password for authentication. Copy this URL for the next section. Be sure that Node.js is selected in the dropdown menu, and run the commands to install the drivers.
Create a .env file in the root directory of your project and set the following variables in it.
For the DB_URL, paste in the URL from the previous section and replace the placeholder with the password you added to the user when you configured the cluster.
Setting up a Twilio account
To set up your Twilio account, sign up for an account and log into your Twilio Console using your account details. Access your Twilio Console dashboard and navigate to the WhatsApp sandbox in your account. This sandbox is designed to enable you to test your application in a development environment without requiring approval from WhatsApp. To access the sandbox, select Messaging from the left-hand menu, followed by Try It Out, and then Send A WhatsApp Message. From the sandbox tab, take note of the Twilio phone number and the join code. You will add the Twilio WhatsApp phone number to your .env file for later use.
Listening to Events and Triggers
In this section, you will learn about the different kinds of database events and how to listen to them. You will also deploy a Twilio serverless function that will run independently of your application. Running a serverless function that performs a particular task when an event occurs in your database is best handled serverless where you abstract scaling and optimization from the main app to the serverless infrastructure.
Create Twilio serverless functions
There are several ways to deploy a Twilio function: using the Twilio serveless toolkit, the API reference, from the console, or using the TwiML Bins. In this guide, we will be deploying from the console. To create your serverless function, log in to your Twilio console and select Functions and Assets from the sidebar menu. Select Overview and click on the Create Service button to create your service. Give your service a friendly name, and click Next to finalize creation. This service will contain all the functions and assets you want to use for a particular project.
When you have successfully created the service, you will see a code playground where you can create as many functions as you want as well as an option to deploy the function to be used in your application. From the sidebar of the code playground, click on the Add button to add an endpoint. Select Add Function and name the path /notify. Paste the code below into the editor, and save.
The code above is a handler function that has context, an event, and a callback function. Here is an explainer of the key parameters:
- The context contains inbuilt Twilio credentials, Twilio instance, and other Twilio toolkits. As you can see, an instance of a Twilio client is initialized from the context.
- The event is the body of the incoming request coming to the function. This is where variables and parameters that will be used within the function are passed and accessed. In the code above, the notification message, WhatsApp numbers of the sender and receiver, and the media for the WhatsApp message are obtained from the event.
- The callback is where callback actions are passed to the function. If you want the function to do something else after it completes its cycle, then the function can be passed as a callback.
You can now deploy the function so it can be accessed publicly from your application. From the playground sidebar, click the Deploy All button to trigger the deployment. Your function can now be accessed via this URL: https://.twil.io/
Add event utility functions
If you cloned the starter project, you will have a setup like the one below. You will be adding new utility functions for overdue book renting, a cron service, and a database event listener in the Rent model.
In the src/events/overdue.js file, you will add this code. This code is responsible for calling our Twilio serverless function which sends a WhatsApp message to overdue borrowers in our book renting application.
In the src/models/rent.model.js file, update the existing code to the one below
The new update to the existing code is the addition of a post-hook function. Mongoose uses a hook to listen to events on the MongoDB database. Hooks can be called before(pre-hook) or after(post-hook) a database operation. In the hook function, the app is listening to a save operation in the Rent model, and when the isOverdue column in the saved data is true, it triggers the notification function.
Set triggers for events function
A trigger is needed to check which rented book is overdue return for the application. This guide uses node-cron, a cron job package that allows you to schedule tasks in Node.js. In the src/utils/cron.js file, add this code:
This code runs every 5 minutes to check for overdue rent by comparing the proposed returnDate and the current date. When it finds any, it updates the isOverdue column to true and saves it to the database . Since our app is listening for a save event in the Rent model, the overdue events function will run and send a message to the borrower on WhatsApp using our serverless function running on Twilio.
Testing and Demo
Your app is now ready for testing. You can start the local development server by running this command:
Once the app runs, you can access it at http://localhost:4000 . To make sure it works well in a live environment, you will use ngrok to generate a live server for your app by running this command.
A live server will be created by ngrok as a proxy to your localhost server as shown below:
With the ngrok live server, you can create users, books, and rentals in the application using tools like Postman or other alternatives for API queries. This demo video shows how to use Postman to test the APIs and also how the cron task is timely triggered to check for overdue rentals and send notifications to the borrower via the Twilio serverless function we deployed earlier.
Conclusion
In this comprehensive guide, you have been able to understand how one can leverage events in the database to run tasks such as notifications and messaging using Twilio serverless functions.
Some key takeaways from the guide are:
- Real-time Notification: By listening to MongoDB database events, you can achieve real-time notifications of changes happening in your database. This ensures that relevant actions are triggered immediately when data is modified, providing timely updates to users or systems.
- Event-Driven Architecture: Implementing event-driven architecture allows for the decoupling of components in your system. This means that changes in one part of the system can trigger actions in another part without direct dependencies, leading to a more modular and scalable architecture.
- Automation of Business Logic: By using MongoDB events to trigger actions like calling a Twilio serverless function, you can automate business logic based on changes in your data. For example, sending SMS notifications to borrowers when their rental overdue status changes.
- Efficiency and Scalability: Handling events asynchronously can improve the efficiency and scalability of your system. Instead of continuously polling the database for changes, you can react only when relevant events occur, reducing unnecessary resource consumption and improving overall performance.
You can learn more about Twilio serverless functions by referring to Twilio’s documentation.
Desmond Obisi is a software engineer and a technical writer who loves doing developer experience engineering. He’s very invested in building products and providing the best experience to users through documentation, guides, building relations, and strategies around products. He can be reached on Twitter, LinkedIn, or through my email desmond.obisi.g20@gmail.com.
Related Posts
Related Resources
Twilio Docs
From APIs to SDKs to sample apps
API reference documentation, SDKs, helper libraries, quickstarts, and tutorials for your language and platform.
Resource Center
The latest ebooks, industry reports, and webinars
Learn from customer engagement experts to improve your own communication.
Ahoy
Twilio's developer community hub
Best practices, code samples, and inspiration to build communications and digital engagement experiences.