Ahmad Awais

SHARE


โšก Practical Guide to Serverless Microsoft Azure Functions with JavaScript

Ahmad AwaisAhmad Awais

As a Full Stack JavaScript developer, I am super excited about this relatively new FaaS or Functions as a Service offering that has also caught on a name of 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.

๐Ÿ‘€ Three Options#

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.

๐Ÿ“˜ Choosing Azure#

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.

Getting Started with Azure Functions#

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.

โš™ What are we building?!#

  1. I am building a serverless Azure function which is based on JavaScript and specifically Node.js code.
  2. This Azure function will get triggered by a simple GET HTTP request from our 3rd party payment solution, i.e., Paddle.com
  3. 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.
  4. 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.
  5. When Azure function receives this GET request, it processes the info, takes out what I need to keep in the MongoDB Atlas Cluster and forms a JavaScript object ready to be saved in the DB.
  6. 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.
  7. 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.

Step#1: Set up Microsoft Azure & VSCode#

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:

  1. โœ… Setup a Microsoft Azure account with a credit card in billing.
  2. โœ… Install Visual Studio Code (Psst. I’m making a course on VSCode).
  3. โœ… Install the Azure Functions extension on your VSCode.
  4. ๐Ÿ’ก To enable local debugging, install the Azure Functions Core Tools.
  5. ๐Ÿ—‚ Create a new directory and open it up in VSCode.

In case you’re wondering which theme and font I am using, it’s ๐Ÿฆ„Shades of Purple โ€” along with my VSCode.pro course. For more info see which software and hardware I use.

7 Vscode Shades Of Puple

Step#2: Create a New Function App Project#

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.

GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions

Step#3: Create an HTTP-triggered Azure Function#

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 Create Function.

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. functions.json and index.js

โšก 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.

GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions

Step#4: Deploy & Test Your Azure Function#

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.

GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions

Step#5: Create package.json and Install mongoose#

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. ๐Ÿ’ฏ

GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions

Step#6: Add App Setting for MongoDB Connection#

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.

GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions

Step#7: Update Node Version of Azure Function#

In the code, I intend to use async/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.

GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions

Step#8: Create MongoDB Model/Schema#

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 and MongoDB.

This file is pretty much self-explanatory.

Step#9: Code the โšกAzure Function with Node.js#

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:

Everything is pretty much explained with inline documentation.

Step#10: Re-Deploy The Azure Function#

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.

GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions>

Step#11: Test Azure Function via Paddle’s Webhook#

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.

GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions

Wow, Humph!!! That was a lot. Glad it worked. ๐ŸŽ‰

๐Ÿค” So, What Just Happened?!#

Prepare yourself for a mouthful.

1๏ธโƒฃ I created a small part of the Sales module 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!

โ€” So, yes, try out Microsoft Azure functions and share your thoughts below, over to you!

๐Ÿ“จ

TheDevTakeaway: Developers' Newsletter!

Takeaway my professional opinion about Open Source, JavaScript/Cloud, Full Stack Development, building a business, growing a family, and everything in between! Delivered to your inbox once a month. ๐Ÿคฃ I'm even funny some times. ๐Ÿ‘ป I hate spam! Pinky Promise!

๐Ÿ‘จโ€๐Ÿซ Edutainer at VSCode.pro ๐ŸŽฉ Full-time #OpenSourcerer ๐Ÿฅ‘ JavaScript Developer Advocate ๐Ÿ˜‚ Hilarious comedian ๐Ÿ”ฅ Ridiculously hard-working Full Stack Web Developer โ“ฆ Regular WordPress Core Developer ๐Ÿ“ฃ TEDx Speaker โœŒ๏ธ Spends 50-80% of his time building professional FOSS (Free & Open Source Software) used by over 218,900 Developers ๐Ÿ™Œ Cloud Community Evangelist ๐ŸŽฏ JavaScript & DevOps fanboy ๐Ÿ’œ Loves his wife (Maedah) ๐Ÿ• Learn more about Ahmad โ†ฃ

Say ๐Ÿ‘‹ on Twitter @MrAhmadAwais | Subscribe to the WordPress Takeaway!