AzureTipsAndTricks/blog/tip148.md

2.3 KiB
Исходник Ответственный История

type title excerpt tags date
post Tip 148 - Share Business Logic between Azure Functions Learn how to run share business logic between Azure Functions
Serverless
2018-08-12 17:00:00

::: tip 💡 Learn more : Azure Functions Documentation. :::

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 dont 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
}