AzureTipsAndTricks/blog/tip148.md

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

Этот файл содержит неоднозначные символы Юникода!

Этот файл содержит неоднозначные символы Юникода, которые могут быть перепутаны с другими в текущей локали. Если это намеренно, можете спокойно проигнорировать это предупреждение. Используйте кнопку Экранировать, чтобы подсветить эти символы.

---
type: post
title: "Tip 148 - Share Business Logic between Azure Functions"
excerpt: "Learn how to run share business logic between Azure Functions"
tags: [Serverless]
date: 2018-08-12 17:00:00
---
::: tip
:bulb: Learn more : [Azure Functions Documentation](https://docs.microsoft.com/azure/azure-functions/?WT.mc_id=docs-azuredevtips-azureappsdev).
:::
### 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:
```javascript
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.
```javascript
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
```json
{
"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
```json
{
"bindings": [
{
"name": "myTimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 */5 * * * *"
}
],
"disabled": false
}
```