Share Business Logic between Azure Functions

 

A common scenario to share business logic between function is: I have an Azure Function that runs daily on a timer trigger and need the same function to run when I request it manually. While the template used may change you basically don’t want to copy/paste the logic into another function. Instead, your function app architecture could look like:

MyFunctionApp
|     host.json
|____ shared
|     |____ businessLogic.js
|____ function1
|     |____ index.js
|     |____ function.json
|____ function2
      |____ index.js
      |____ function.json

In the shared folder, you’d create a file named businessLogic.js and put your shared code.

A sample in JS could be the following:

module.exports = function (context, req) {
    context.res = {
        body: "<b>Hello World, from Azure Tips and Tricks</b>",
        status: 201,
        headers: {
            'content-type': "text/html"
        }
    };     
    context.done();
};

Then you’d create two separate functions called function1 and function2.

Then in your function1/index.js and function2/index.js, you would use the following lines of code that reference the shared logic folder and file.

var logic = require("../shared/businessLogic.js");
module.exports = logic;

Notice that each function has their own function.json file. So here you could define them to be different triggers such as function1 could be an HTTP Trigger

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ],
  "disabled": false
}

and function2 could be a Timer Trigger

{
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 */5 * * * *"
    }
  ],
  "disabled": false
}

As always, I hoped this help someone out there!

Read 360 times
Dylan Austin

About:

Whenever I have a problem, I sing. Then I realize my voice is worse than my problem.

Top
We use cookies to improve our website. By continuing to use this website, you are giving consent to cookies being used. More details…