Serverless — since you don't have to manage, update, patch, or worry about servers.
While building this custom WordPress dashboard, I wanted to make sure that each module of this dashboard lived in form of a serverless app with multiple serverless functions. This decision was based on keeping this dashboard's cost as economical as possible.
There are three major cloud services providers present. That are Microsoft Azure, Google Cloud Platform, and Amazon Web Services. Each of which has serverless functions available which are called Azure functions, GCP Cloud Functions, and AWS Lambdas.
Azure has one of the biggest cloud architecture and global presence. 50 Azure regions, more than any cloud provider and after testing each of these three, I found that Azure functions had the best response time in UAE (as my client's business is based out of UAE).
Also, the fact that we're using Azure ML Studio, AI Cognitive Services, and Virtual Machines to host parts of this project, it made complete sense to use Azure functions for the serverless architecture.
Let's get started with Azure functions. I am going to take you through the process of creating a simple serverless Azure function, which will be triggered via HTTP requests, and inside it, we'll process the sales information sent to us from Paddle.com.
- This Azure function will get triggered by a simple
GETHTTP request from our 3rd party payment solution, i.e., Paddle.com
- As soon as there's a sale on Paddle.com, it will trigger a webhook that contains info related to our sale, quantity, item, earnings, and some member-related data that WordPress sent to Paddle.
- Using WordPress REST API, I have added some custom data related to the user who purchased the product, like user's ID in WordPress DB, which WordPress site had this sale, and such user's meta info.
- When Azure function receives this
- The azure function then connects to MongoDB Atlas instance via an npm package called mongoose, where after connecting the database, I create a DB Model/Schema, and then this data is saved to the MongoDB Atlas Cluster.
- After which Azure function kind of sits there waiting for next sale to happen, where my client only pays for the execution time and amount of executions for Azure functions. (1 million of which are free every month 😮).
Now, this is only a high-level summary of what's happening, there's a lot of steps that I skipped here like authentication which is beyond the scope of this article. You should always setup authentication and verification to keep things civil and avoid any overage.
So, let's go ahead and build this thing.
I expect you to have the Azure account set up on your end. You'll need to subscribe with a credit card since we need storage for hosting the Node.js files which will be used with Azure Functions and you have to pay for storage (you'll probably get a free $200 credit for the first month and even after that the cost is quite pretty low). So, go ahead and set up the following:
- ✅ Setup a Microsoft Azure account with a credit card in billing.
- ✅ Install Visual Studio Code (Psst. I'm making a course on VSCode).
- ✅ Install the Azure Functions extension on your VSCode.
- 💡 To enable local debugging, install the Azure Functions Core Tools.
- 🗂 Create a new directory and open it up in VSCode.
Now let's create a new function app project. This is really easy with VSCode. All you have to do is go-to the Azure Extension explorer present in the activity bar. From there access
FUNCTIONS tab and click on the first
Create New Project icon.
This will create a demo project, with basic files required to get started and will initialize a Git repo for you. I'll keep up with small gif based demos to make things easier for you.
Now that we have created a function app project, let's create an HTTP-triggered serverless Azure function. For that, go-to the Azure Extension explorer present in the activity bar. From there access
FUNCTIONS tab and click on the second icon
For the sake of this demo, I am choosing to keep the authentication part simple so going to select anonymous access. The name of our Azure function is
HttpTriggerJS so you can find a new directory created with that name inside your project. This should contain two files i.e.
⚡ A function is a primary concept in Azure Functions. You write code for a function in a language of your choice and save the code and configuration files in the same folder.
🛠 The configuration is named
function.json, which contains JSON configuration data. It defines the function bindings and other configuration settings. The runtime uses this file to determine the events to monitor and how to pass data into and return data from function execution. Read more on this file in the official documentation here.
Following is an example
function.json file that gets created.
And then, there's an
index.js file which contains a basic code that you can use to test your Azure function. It receives a parameter
name and prints it back to you or shows you an error asking for this parameter.
Now that we have created an Azure function which can be triggered by
GET HTTP request, let's go ahead and deploy it with VSCode and test it with Postman API Explorer.
To deploy the function go-to the Azure Extension explorer present in the activity bar. From there access
FUNCTIONS tab and click on the third icon
Deploy to Function App.
This will ask you a bunch of questions about what is the name of your app, use anything unique. I used
demo-wp-mdb-azure— VSCode then use this to create a resource group, to group together your function-app related resources, it's storage (used to save the files), and the created Azure function — finally responding us back with a public URL.
I then went ahead to access this URL and it asked for the
name param as per the code then when I sent the
name param with the Postman app, it responded with
Hello Ahmad Awais. 👍
VSCode also asked me to update the function extension app version to beta, and I chose yes — coz that will help me use Node.js v8 for async/await.
package.json and Install
Now that our Azure function is up and running. Let's create a
package.json file in the root of our project and install
mongoose. We'll need this to connect and save data to our MongoDB Atlas Cluster.
Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in typecasting, validation, query building, business logic hooks and more, out of the box. It's pretty awesome. 💯
Now we are almost ready to start writing code for our application. But before doing that, we'll need a connection string to be able to connect to our MongoDB Atlas Cluster (just like we did with MongoDB Compass). This connection string is private and you shouldn't commit it to the git repo.
💯 This connections string belongs to the
local.settings.json file in the project root. Let's first download the settings, then add
MongodbAtlas setting with our connection string (get this string from the MongoDB Atlas dashboard) and upload the app settings.
To do this, go-to the Azure Extension explorer present in the activity bar. From there access
FUNCTIONS tab and select your subscription, then your Azure function app, i.e.,
demo-wp-mdb-azure and then right click
Application Settings to select
Download remote settings… to download and
Upload local settings… to upload the settings after adding the
MongodbAtlas connection string to the settings.
In the code, I intend to use
await which are not available on
v6.5.0 of Node.js that comes with the default version 1 of Azure functions. In the step #4, VSCode asked me to update to the runtime version of Azure function to beta and I did that. This enables support for latest Node.js versions on Azure functions.
So, let's just update
WEBSITE_NODE_DEFAULT_VERSION app setting in our local settings and update that to the remote settings.
Before we save any data to our MongoDB Atlas Cluster, let's create a
modelSale.js file that will contain the model's schema for what we intend to save in the database. It's an extremely simple schema implementation, I suggest you read up on what you can do here with
[mongoose](http://mongoosejs.com/docs/guide.html) and MongoDB.
This file is pretty much self-explanatory.
Now let's code our Azure function. I'm adding all the main code lives inside the
index.js file for the purpose of this demo. Also going to use the context object as the first parameter, make sure you read about that. Everything else is explained in the code snippet below.
So, this is just a demo code for this article. It does the following:
- ✅ Gets the data from Paddle.com
- ⚡ Connects to the MongoDB Atlas via connection string that we added in our Application Settings.
- 📘 Uses the defined DB schema inside the
testdatabase where it creates a
salescollection including documents for our sales.
- ⚙ Validates the data and creates a
finalDataobject that gets saved in the MongoDB Atlas Cluster. Yay!!!
- 🥅 Finally, responds to the Paddle webhook with
200status code if all goes well, and does the
Everything is pretty much explained with inline documentation.
Now let's re-deploy the Azure function. For that, go-to the Azure Extension explorer present in the activity bar. From there access
FUNCTIONS tab and click on the third
Deploy to Function App icon.
Looks like we're pretty much done. All that's left is to test our Azure function by triggering a dummy webhook via Paddle.com. Let's do that. Also, when things do work, let's explore how our data looks in the MongoDB Compass.
Checkout this 8Mb Gif that won't load here →
Wow, Humph!!! That was a lot. Glad it worked. 🎉
Prepare yourself for a mouthful.
- 1️⃣ I created a small part of the
Salesmodule in the custom WordPress Dashboard app that I am building
- 2️⃣ I used MongoDB Atlas and Compass, then created Microsoft ⚡Azure Function via Function App with VSCode
- 3️⃣ I deployed the app with env secret as application string with the MongoDB connection string
- 4️⃣ I then updated the Node.js version for Azure functions
- 5️⃣ And then I triggered the function via a dummy webhook from Paddle.com (like it will get triggered when an actual sale will happen) to send data (from Paddle + WordPress) to our Azure function and from there to MongoDB Atlas.
- ✅ And it worked, haha!
That's about it. To read more about this topic, take this gigantic post for a read" Building a custom WordPress dashboard with Azure Functions & MongoDB →
— So, yes, try out Microsoft Azure functions (serverless stuff is pretty cool) and share your thoughts below, over to you! Peace! ✌️
Follow me on Twitter for where I share #OneDevMinute tips @MrAhmadAwais →