Azure Tips and Tricks Part 148 - Share Business Logic between Azure Functions

1 minute read

The Complete List of Azure Tips and Tricks

Available Now!

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!

Want more Azure Tips and Tricks?

If you’d like to learn more Azure Tips and Tricks, then follow me on twitter or stay tuned to this blog! I’d also love to hear your tips and tricks for working in Azure, just leave a comment below.

Leave a Comment