Exercise: Use a JavaScript Library in Azure Functions

Challenge

Take the Azure function created in Exercise: Write an Azure Function in JavaScript to Return the Current Date and modify it to tell you the number of sleeps until a date in the future. Use a third-party JS library to do the date arithmetic.

Solution Steps

I’m going to use the Moment.js library to do date manipulation. With Moment.js installed the calculation of dates between two dates is relatively simple:

function sleepsuntil(target_date) {
// target_date should be a moment.js object
const today = (new moment()).startOf("day");
result = target_date.diff(today, "days");
return Math.max(0, result); // No sleeps to a date in the past
}

The challenge comes in how to use Moment.js from an Azure function.

      1. The Microsoft documentation briefly touches on JS package management in Azure
      2. You need to add a npm style package.json file into the folder on Azure that holds the code for your function
      3. To access the Azure Functions folders you need to open the “Advanced Tools (Kudu)” menu. Like this…open_kudu
      4. Using a local console with node installed use the npm tools to create a package.json file with the dependency to moment.js:
        npm init
        npm install moment --save
      5. That results in a package.json file like this:
        {
          "name": "sleepsuntil",
          "version": "1.0.0",
          "description": "How many sleeps until a given date",
          "main": "index.js",
          "scripts": {
            "test": "echo \"Error: no test specified\" && exit 1"
          },
          "author": "",
          "license": "ISC",
          "dependencies": {
            "moment": "^2.21.0"
          }
        }
        
      6. You can now navigate in the Kudu console to the folder containing the HTTP Trigger. To do this after starting Kudu you click: Debug console -> CMD -> site -> wwwroot -> HttpTriggerJS1
      7. You now drag-and-drop your package.json file from your local machine up into the Azure Portal. The folder should end up looking like this:kudu-folder
      8. In the command window at the bottom of the Kudu screen type:
         npm install
      9. The system should report back that it has installed moment for you. It will probably also complain you haven’t set up the repository field.
      10. We’re nearly there. All is left to do is update the function to use input from the browser and return the number of days calculated by moment:
        module.exports = function (context, req) {
            var moment = require("moment");
            function sleepsuntil(target_date) {
                // target_date should be a moment.js object
                const today = (new moment()).startOf("day");
                result = target_date.diff(today, "days");
                return Math.max(0, result); // No sleeps to a date in the past
            }
        
            if (req.query.year &&
                req.query.month &&
                req.query.day) {
        
                    const target = moment({year: req.query.year,
                                           month: (parseInt(req.query.month) - 1), // JS Dates are zero indexed!!!
                                           day: req.query.day });
        
                    context.res = {
                        body: sleepsuntil(target)
                    };
            }
            else {
                context.res = {
                    status: 400,
                    body: "Please pass a year, month, and day."
                };
            }
            context.done();
        };
        

Exercise: Write an Azure Function in JavaScript to Return the Current Date

Challenge

Here’s a starter exercise for Azure Functions: write a function to return the current date.

Solution Steps

  1. The first set of tasks are all around getting a function set up on https://portal.azure.com/
  2. Log in to the Azure portal
  3. Make a resource group “learning”. We’ll use this in the future to organise all Azure resources associated with throw-away learning tasks
  4. Add a “Function App” called “datenow”
    • OS = Windows
    • Located = UK West
    • Create new storage
  5. In the function app create new function of type “HTTP Trigger” and language JavaScript
  6. When the app is created it adds a helpful example function. A small amount of modification results in the function returning the current date:
    module.exports = function (context, req) {
        context.log('JavaScript HTTP trigger function processed a request.');
        const now = new Date()
        context.res = {
            // status: 200, /* Defaults to 200 */
            body: now
        };
        context.done();
    };
    

     

  7. Notice how the Azure functions framework handles the encoding of the JavaScript Date object correctly based on the content negotiated with the requestor. Using a HTTP testing tool, like Postman for Chrome, if you specify “Accept: text/json” then you get a JSON represnation back; specifcy “Accept: text/xml” and XML is returned

 

Python Snippet to Hash Email Addresses

I wanted to process some email address data today but hide the real email addresses. To do that I chose to run the SHA-256 hash over the email address data. Here’s the python snippet I used to convert the plain emails to the hashed versions (ignoring any emails with anything other than ASCII characters for simplicity):


import hashlib

plain_emails = ["user1@address1",
                "user2@address2"]

hashed_emails = [hashlib.sha256(bytes(mail.lower(), "ascii")).hexdigest()
                 for mail
                 in plain_emails]