├── .github └── CODEOWNERS ├── .gitignore ├── LICENSE ├── README.md ├── SECURITY.md ├── azure-pipelines ├── code-mirror.yml └── public-build.yml ├── js ├── .eslintrc.json ├── .funcignore ├── .gitignore ├── .prettierignore ├── .prettierrc ├── .vscode │ ├── extensions.json │ ├── launch.json │ ├── settings.json │ └── tasks.json ├── host.json ├── package-lock.json ├── package.json └── src │ ├── appHooks1.js │ ├── functions │ ├── cosmosDBTrigger1.js │ ├── cosmosInput1.js │ ├── cosmosInput2.js │ ├── cosmosInput3.js │ ├── cosmosInput4.js │ ├── cosmosOutput1.js │ ├── cosmosOutput2.js │ ├── eventGridOutput1.js │ ├── eventGridOutput2.js │ ├── eventGridTrigger1.js │ ├── eventHubOutput1.js │ ├── eventHubOutput2.js │ ├── eventHubTrigger1.js │ ├── eventHubTrigger2.js │ ├── httpTrigger1.js │ ├── httpTrigger2.js │ ├── httpTrigger3.js │ ├── httpTriggerBadAsync.js │ ├── httpTriggerGoodAsync.js │ ├── httpTriggerStreamRequest.js │ ├── httpTriggerStreamResponse.js │ ├── serviceBusOutput1.js │ ├── serviceBusOutput2.js │ ├── serviceBusTrigger1.js │ ├── sqlInput1.js │ ├── sqlInput2.js │ ├── sqlInput3.js │ ├── sqlOutput1.js │ ├── sqlOutput2.js │ ├── storageBlobInputAndOutput1.js │ ├── storageBlobTrigger1.js │ ├── storageBlobTrigger2.js │ ├── storageBlobTriggerEventGrid1.js │ ├── storageQueueOutput1.js │ ├── storageQueueOutput2.js │ ├── storageQueueTrigger1.js │ ├── tableInput1.js │ ├── tableOutput1.js │ ├── timerTrigger1.js │ ├── timerTriggerWithRetry.js │ └── warmupTrigger.js │ ├── invocationHooks1.js │ ├── otelAppInsights.js │ └── otelOtlp.js └── ts ├── .eslintrc.json ├── .funcignore ├── .gitignore ├── .prettierignore ├── .prettierrc ├── .vscode ├── extensions.json ├── launch.json ├── settings.json └── tasks.json ├── host.json ├── package-lock.json ├── package.json ├── src ├── appHooks1.ts ├── functions │ ├── cosmosDBTrigger1.ts │ ├── cosmosInput1.ts │ ├── cosmosInput2.ts │ ├── cosmosInput3.ts │ ├── cosmosInput4.ts │ ├── cosmosOutput1.ts │ ├── cosmosOutput2.ts │ ├── eventGridOutput1.ts │ ├── eventGridOutput2.ts │ ├── eventGridTrigger1.ts │ ├── eventHubOutput1.ts │ ├── eventHubOutput2.ts │ ├── eventHubTrigger1.ts │ ├── eventHubTrigger2.ts │ ├── httpTrigger1.ts │ ├── httpTrigger2.ts │ ├── httpTrigger3.ts │ ├── httpTriggerBadAsync.ts │ ├── httpTriggerGoodAsync.ts │ ├── httpTriggerStreamRequest.ts │ ├── httpTriggerStreamResponse.ts │ ├── serviceBusOutput1.ts │ ├── serviceBusOutput2.ts │ ├── serviceBusTrigger1.ts │ ├── sqlInput1.ts │ ├── sqlInput2.ts │ ├── sqlInput3.ts │ ├── sqlOutput1.ts │ ├── sqlOutput2.ts │ ├── storageBlobInputAndOutput1.ts │ ├── storageBlobTrigger1.ts │ ├── storageBlobTriggerEventGrid1.ts │ ├── storageQueueOutput1.ts │ ├── storageQueueOutput2.ts │ ├── storageQueueTrigger1.ts │ ├── tableInput1.ts │ ├── tableOutput1.ts │ ├── timerTrigger1.ts │ ├── timerTriggerWithRetry.ts │ └── warmupTrigger1.ts ├── invocationHooks1.ts ├── otelAppInsights.ts └── otelOtlp.ts └── tsconfig.json /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @azure/azure-functions-nodejs -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # nyc test coverage 18 | .nyc_output 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | build/Release 28 | 29 | # Dependency directories 30 | node_modules 31 | jspm_packages 32 | 33 | # Optional npm cache directory 34 | .npm 35 | 36 | # Optional REPL history 37 | .node_repl_history 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) .NET Foundation. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Azure Functions Node.js Samples 2 | 3 | [![Build Status](https://img.shields.io/azure-devops/build/azfunc/public/505/main)](https://azfunc.visualstudio.com/public/_build/latest?definitionId=505&branchName=main) 4 | 5 | This repo is used to hold the samples for the "Triggers and bindings" docs. For example, this [storage queue trigger doc](https://learn.microsoft.com/azure/azure-functions/functions-bindings-storage-queue-trigger?pivots=programming-language-javascript). This repo currently supports programming model v4, for both JavaScript and TypeScript. 6 | 7 | ## Repositories 8 | 9 | These are the most important GitHub repositories that make up the Node.js experience on Azure Functions: 10 | 11 | - [azure-functions-nodejs-library](https://github.com/Azure/azure-functions-nodejs-library): The `@azure/functions` [npm package](https://www.npmjs.com/package/@azure/functions) that you include in your app. 12 | - [azure-functions-nodejs-worker](https://github.com/Azure/azure-functions-nodejs-worker): The other half of the Node.js experience that ships directly in Azure. 13 | - [azure-functions-nodejs-e2e-tests](https://github.com/Azure/azure-functions-e2e-tests): A set of automated end-to-end tests designed to run against prerelease versions of all Node.js components. 14 | - [azure-functions-nodejs-samples](https://github.com/Azure/azure-functions-samples): Samples displayed in the official Microsoft docs. 15 | - [azure-functions-host](https://github.com/Azure/azure-functions-host): The runtime shared by all languages in Azure Functions. 16 | - [azure-functions-core-tools](https://github.com/Azure/azure-functions-core-tools): The CLI used to test Azure Functions locally. 17 | 18 | ## Contributing 19 | 20 | - Clone the repository locally and open the `js` or `ts` folder in VS Code 21 | - Run "Extensions: Show Recommended Extensions" from the [command palette](https://code.visualstudio.com/docs/getstarted/userinterface#_command-palette) and install all extensions listed under "Workspace Recommendations" 22 | - Run `npm install` 23 | - If using TypeScript, run `npm run build` 24 | 25 | The apps in this repository are not setup to be run directly. You should validate your code in a separate app. 26 | 27 | ### Adding a new file 28 | 29 | If you're adding a brand new file, you'll have to add a reference to it in the Microsoft docs repos. Here are the repos: 30 | 31 | - Public: 32 | - Internal-only: 33 | 34 | Here is an example of how to reference a whole file: 35 | 36 | ```markdown 37 | :::code language="typescript" source="~/azure-functions-nodejs-v4/ts/src/functions/serviceBusOutput1.ts" ::: 38 | ``` 39 | 40 | Here is an example of how to reference part of a file: 41 | 42 | ```markdown 43 | :::code language="typescript" source="~/azure-functions-nodejs-v4/ts/src/functions/serviceBusOutput2.ts" id="displayInDocs" ::: 44 | ``` 45 | 46 | > NOTE: The relevant file must define the region to display with comments like `// ` and `// ` 47 | 48 | ### Code of Conduct 49 | 50 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 51 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Security 4 | 5 | Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). 6 | 7 | If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below. 8 | 9 | ## Reporting Security Issues 10 | 11 | **Please do not report security vulnerabilities through public GitHub issues.** 12 | 13 | Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report). 14 | 15 | If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey). 16 | 17 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc). 18 | 19 | Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: 20 | 21 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) 22 | * Full paths of source file(s) related to the manifestation of the issue 23 | * The location of the affected source code (tag/branch/commit or direct URL) 24 | * Any special configuration required to reproduce the issue 25 | * Step-by-step instructions to reproduce the issue 26 | * Proof-of-concept or exploit code (if possible) 27 | * Impact of the issue, including how an attacker might exploit the issue 28 | 29 | This information will help us triage your report more quickly. 30 | 31 | If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs. 32 | 33 | ## Preferred Languages 34 | 35 | We prefer all communications to be in English. 36 | 37 | ## Policy 38 | 39 | Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd). 40 | 41 | 42 | -------------------------------------------------------------------------------- /azure-pipelines/code-mirror.yml: -------------------------------------------------------------------------------- 1 | trigger: 2 | branches: 3 | include: 4 | - main 5 | 6 | resources: 7 | repositories: 8 | - repository: eng 9 | type: git 10 | name: engineering 11 | ref: refs/tags/release 12 | 13 | variables: 14 | - template: ci/variables/cfs.yml@eng 15 | 16 | extends: 17 | template: ci/code-mirror.yml@eng -------------------------------------------------------------------------------- /azure-pipelines/public-build.yml: -------------------------------------------------------------------------------- 1 | # This build is used for public PR and CI builds. 2 | 3 | trigger: 4 | batch: true 5 | branches: 6 | include: 7 | - main 8 | 9 | pr: 10 | branches: 11 | include: 12 | - main 13 | 14 | schedules: 15 | - cron: "30 10 * * *" 16 | displayName: Nightly build 17 | always: true 18 | branches: 19 | include: 20 | - main 21 | 22 | resources: 23 | repositories: 24 | - repository: 1es 25 | type: git 26 | name: 1ESPipelineTemplates/1ESPipelineTemplates 27 | ref: refs/tags/release 28 | 29 | extends: 30 | template: v1/1ES.Unofficial.PipelineTemplate.yml@1es 31 | parameters: 32 | pool: 33 | name: 1es-pool-azfunc-public 34 | image: 1es-windows-2022 35 | os: windows 36 | 37 | sdl: 38 | codeql: 39 | compiled: 40 | enabled: true 41 | runSourceLanguagesInSourceAnalysis: true 42 | 43 | settings: 44 | # PR's from forks do not have sufficient permissions to set tags. 45 | skipBuildTagsForGitHubPullRequests: ${{ variables['System.PullRequest.IsFork'] }} 46 | 47 | stages: 48 | - stage: Build 49 | jobs: 50 | - job: Build 51 | strategy: 52 | matrix: 53 | NODE18: 54 | NODE_VERSION: "18.x" 55 | NODE20: 56 | NODE_VERSION: "20.x" 57 | NODE22: 58 | NODE_VERSION: "22.x" 59 | steps: 60 | - task: NodeTool@0 61 | inputs: 62 | versionSpec: $(NODE_VERSION) 63 | displayName: "Install Node.js" 64 | - script: npm ci 65 | displayName: "npm ci (ts)" 66 | workingDirectory: "ts" 67 | - script: npm run build 68 | displayName: "npm run build (ts)" 69 | workingDirectory: "ts" 70 | - script: npm run lint 71 | displayName: "npm run lint (ts)" 72 | workingDirectory: "ts" 73 | - script: npm ci 74 | displayName: "npm ci (js)" 75 | workingDirectory: "js" 76 | - script: npm run lint 77 | displayName: "npm run lint (js)" 78 | workingDirectory: "js" 79 | -------------------------------------------------------------------------------- /js/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "node": true, 4 | "es6": true 5 | }, 6 | "parserOptions": { 7 | "ecmaVersion": "latest" 8 | }, 9 | "plugins": ["simple-import-sort", "import"], 10 | "extends": ["eslint:recommended", "plugin:prettier/recommended"], 11 | "rules": { 12 | "prefer-const": ["error", { "destructuring": "all" }], 13 | "no-return-await": "off", 14 | "eqeqeq": "error", 15 | "no-unused-vars": "off", 16 | "simple-import-sort/imports": [ 17 | "error", 18 | { 19 | "groups": [["^\\u0000", "^node:", "^@?\\w", "^", "^\\."]] 20 | } 21 | ], 22 | "simple-import-sort/exports": "error", 23 | "import/first": "error", 24 | "import/newline-after-import": "error", 25 | "import/no-duplicates": "error" 26 | }, 27 | "ignorePatterns": [] 28 | } 29 | -------------------------------------------------------------------------------- /js/.funcignore: -------------------------------------------------------------------------------- 1 | *.js.map 2 | *.ts 3 | .git* 4 | .vscode 5 | __azurite_db*__.json 6 | __blobstorage__ 7 | __queuestorage__ 8 | local.settings.json 9 | test 10 | tsconfig.json -------------------------------------------------------------------------------- /js/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | 24 | # nyc test coverage 25 | .nyc_output 26 | 27 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 28 | .grunt 29 | 30 | # Bower dependency directory (https://bower.io/) 31 | bower_components 32 | 33 | # node-waf configuration 34 | .lock-wscript 35 | 36 | # Compiled binary addons (https://nodejs.org/api/addons.html) 37 | build/Release 38 | 39 | # Dependency directories 40 | node_modules/ 41 | jspm_packages/ 42 | 43 | # TypeScript v1 declaration files 44 | typings/ 45 | 46 | # Optional npm cache directory 47 | .npm 48 | 49 | # Optional eslint cache 50 | .eslintcache 51 | 52 | # Optional REPL history 53 | .node_repl_history 54 | 55 | # Output of 'npm pack' 56 | *.tgz 57 | 58 | # Yarn Integrity file 59 | .yarn-integrity 60 | 61 | # dotenv environment variables file 62 | .env 63 | .env.test 64 | 65 | # parcel-bundler cache (https://parceljs.org/) 66 | .cache 67 | 68 | # next.js build output 69 | .next 70 | 71 | # nuxt.js build output 72 | .nuxt 73 | 74 | # vuepress build output 75 | .vuepress/dist 76 | 77 | # Serverless directories 78 | .serverless/ 79 | 80 | # FuseBox cache 81 | .fusebox/ 82 | 83 | # DynamoDB Local files 84 | .dynamodb/ 85 | 86 | # TypeScript output 87 | dist 88 | out 89 | 90 | # Azure Functions artifacts 91 | bin 92 | obj 93 | appsettings.json 94 | local.settings.json 95 | 96 | # Azurite artifacts 97 | __blobstorage__ 98 | __queuestorage__ 99 | __azurite_db*__.json -------------------------------------------------------------------------------- /js/.prettierignore: -------------------------------------------------------------------------------- 1 | out 2 | dist 3 | node_modules 4 | 5 | # Exclude markdown until this bug is fixed: https://github.com/prettier/prettier/issues/5019 6 | *.md -------------------------------------------------------------------------------- /js/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 4, 3 | "singleQuote": true, 4 | "printWidth": 120, 5 | "endOfLine": "auto" 6 | } 7 | -------------------------------------------------------------------------------- /js/.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": ["ms-azuretools.vscode-azurefunctions", "dbaeumer.vscode-eslint", "esbenp.prettier-vscode"] 3 | } 4 | -------------------------------------------------------------------------------- /js/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Attach to Node Functions", 6 | "type": "node", 7 | "request": "attach", 8 | "port": 9229, 9 | "preLaunchTask": "func: host start" 10 | } 11 | ] 12 | } 13 | -------------------------------------------------------------------------------- /js/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "azureFunctions.deploySubpath": ".", 3 | "azureFunctions.postDeployTask": "npm install (functions)", 4 | "azureFunctions.projectLanguage": "JavaScript", 5 | "azureFunctions.projectRuntime": "~4", 6 | "debug.internalConsoleOptions": "neverOpen", 7 | "azureFunctions.projectLanguageModel": 4, 8 | "azureFunctions.preDeployTask": "npm prune (functions)", 9 | "editor.codeActionsOnSave": ["source.fixAll"], 10 | "editor.formatOnSave": true, 11 | "editor.defaultFormatter": "esbenp.prettier-vscode" 12 | } 13 | -------------------------------------------------------------------------------- /js/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "type": "func", 6 | "label": "func: host start", 7 | "command": "host start", 8 | "problemMatcher": "$func-node-watch", 9 | "isBackground": true, 10 | "dependsOn": "npm install (functions)" 11 | }, 12 | { 13 | "type": "shell", 14 | "label": "npm install (functions)", 15 | "command": "npm install" 16 | }, 17 | { 18 | "type": "shell", 19 | "label": "npm prune (functions)", 20 | "command": "npm prune --production", 21 | "problemMatcher": [] 22 | } 23 | ] 24 | } 25 | -------------------------------------------------------------------------------- /js/host.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0", 3 | "logging": { 4 | "applicationInsights": { 5 | "samplingSettings": { 6 | "isEnabled": true, 7 | "excludedTypes": "Request" 8 | } 9 | } 10 | }, 11 | "extensionBundle": { 12 | "id": "Microsoft.Azure.Functions.ExtensionBundle", 13 | "version": "[3.15.0, 4.0.0)" 14 | }, 15 | "concurrency": { 16 | "dynamicConcurrencyEnabled": true, 17 | "snapshotPersistenceEnabled": true 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /js/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "triggerdocs", 3 | "version": "1.0.0", 4 | "description": "", 5 | "scripts": { 6 | "lint": "eslint . --fix", 7 | "format": "prettier . --write", 8 | "start": "func start", 9 | "test": "echo \"No tests yet...\"" 10 | }, 11 | "dependencies": { 12 | "@azure/functions": "^4.5.0", 13 | "@azure/functions-opentelemetry-instrumentation": "^0.1.0", 14 | "@azure/monitor-opentelemetry-exporter": "^1.0.0-beta.23", 15 | "@opentelemetry/api": "^1.8.0", 16 | "@opentelemetry/auto-instrumentations-node": "^0.46.1", 17 | "@opentelemetry/exporter-logs-otlp-http": "^0.51.1" 18 | }, 19 | "devDependencies": { 20 | "eslint": "^7.32.0", 21 | "eslint-config-prettier": "^8.3.0", 22 | "eslint-plugin-import": "^2.29.0", 23 | "eslint-plugin-prettier": "^4.0.0", 24 | "eslint-plugin-simple-import-sort": "^10.0.0", 25 | "prettier": "^2.4.1" 26 | }, 27 | "main": "src/functions/httpTrigger1.js" 28 | } 29 | -------------------------------------------------------------------------------- /js/src/appHooks1.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | 3 | app.hook.appStart((context) => { 4 | // add your logic here 5 | }); 6 | 7 | app.hook.appTerminate((context) => { 8 | // add your logic here 9 | }); 10 | -------------------------------------------------------------------------------- /js/src/functions/cosmosDBTrigger1.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | 3 | app.cosmosDB('cosmosDBTrigger1', { 4 | connection: '', 5 | databaseName: 'Tasks', 6 | containerName: 'Items', 7 | createLeaseContainerIfNotExists: true, 8 | handler: (documents, context) => { 9 | context.log(`Cosmos DB function processed ${documents.length} documents`); 10 | }, 11 | }); 12 | -------------------------------------------------------------------------------- /js/src/functions/cosmosInput1.js: -------------------------------------------------------------------------------- 1 | const { app, input, output } = require('@azure/functions'); 2 | 3 | const cosmosInput = input.cosmosDB({ 4 | databaseName: 'MyDatabase', 5 | collectionName: 'MyCollection', 6 | id: '{queueTrigger}', 7 | partitionKey: '{queueTrigger}', 8 | connectionStringSetting: 'MyAccount_COSMOSDB', 9 | }); 10 | 11 | const cosmosOutput = output.cosmosDB({ 12 | databaseName: 'MyDatabase', 13 | collectionName: 'MyCollection', 14 | createIfNotExists: false, 15 | partitionKey: '{queueTrigger}', 16 | connectionStringSetting: 'MyAccount_COSMOSDB', 17 | }); 18 | 19 | app.storageQueue('storageQueueTrigger1', { 20 | queueName: 'outqueue', 21 | connection: 'MyStorageConnectionAppSetting', 22 | extraInputs: [cosmosInput], 23 | extraOutputs: [cosmosOutput], 24 | handler: (queueItem, context) => { 25 | const doc = context.extraInputs.get(cosmosInput); 26 | doc.text = 'This was updated!'; 27 | context.extraOutputs.set(cosmosOutput, doc); 28 | }, 29 | }); 30 | -------------------------------------------------------------------------------- /js/src/functions/cosmosInput2.js: -------------------------------------------------------------------------------- 1 | const { app, input } = require('@azure/functions'); 2 | 3 | const cosmosInput = input.cosmosDB({ 4 | databaseName: 'ToDoItems', 5 | collectionName: 'Items', 6 | id: '{Query.id}', 7 | partitionKey: '{Query.partitionKeyValue}', 8 | connectionStringSetting: 'CosmosDBConnection', 9 | }); 10 | 11 | app.http('httpTrigger1', { 12 | methods: ['GET', 'POST'], 13 | authLevel: 'anonymous', 14 | extraInputs: [cosmosInput], 15 | handler: (request, context) => { 16 | const toDoItem = context.extraInputs.get(cosmosInput); 17 | if (!toDoItem) { 18 | return { 19 | status: 404, 20 | body: 'ToDo item not found', 21 | }; 22 | } else { 23 | return { 24 | body: `Found ToDo item, Description=${toDoItem.Description}`, 25 | }; 26 | } 27 | }, 28 | }); 29 | -------------------------------------------------------------------------------- /js/src/functions/cosmosInput3.js: -------------------------------------------------------------------------------- 1 | const { app, input } = require('@azure/functions'); 2 | 3 | const cosmosInput = input.cosmosDB({ 4 | databaseName: 'ToDoItems', 5 | collectionName: 'Items', 6 | id: '{id}', 7 | partitionKey: '{partitionKeyValue}', 8 | connectionStringSetting: 'CosmosDBConnection', 9 | }); 10 | 11 | app.http('httpTrigger1', { 12 | methods: ['GET', 'POST'], 13 | authLevel: 'anonymous', 14 | route: 'todoitems/{partitionKeyValue}/{id}', 15 | extraInputs: [cosmosInput], 16 | handler: (request, context) => { 17 | const toDoItem = context.extraInputs.get(cosmosInput); 18 | if (!toDoItem) { 19 | return { 20 | status: 404, 21 | body: 'ToDo item not found', 22 | }; 23 | } else { 24 | return { 25 | body: `Found ToDo item, Description=${toDoItem.Description}`, 26 | }; 27 | } 28 | }, 29 | }); 30 | -------------------------------------------------------------------------------- /js/src/functions/cosmosInput4.js: -------------------------------------------------------------------------------- 1 | const { app, input } = require('@azure/functions'); 2 | 3 | const cosmosInput = input.cosmosDB({ 4 | databaseName: 'MyDb', 5 | collectionName: 'MyCollection', 6 | sqlQuery: 'SELECT * from c where c.departmentId = {departmentId}', 7 | connectionStringSetting: 'CosmosDBConnection', 8 | }); 9 | 10 | app.storageQueue('storageQueueTrigger1', { 11 | queueName: 'outqueue', 12 | connection: 'MyStorageConnectionAppSetting', 13 | extraInputs: [cosmosInput], 14 | handler: (queueItem, context) => { 15 | const documents = context.extraInputs.get(cosmosInput); 16 | for (const document of documents) { 17 | // operate on each document 18 | } 19 | }, 20 | }); 21 | -------------------------------------------------------------------------------- /js/src/functions/cosmosOutput1.js: -------------------------------------------------------------------------------- 1 | const { app, output } = require('@azure/functions'); 2 | 3 | const cosmosOutput = output.cosmosDB({ 4 | databaseName: 'MyDatabase', 5 | collectionName: 'MyCollection', 6 | createIfNotExists: true, 7 | connectionStringSetting: 'MyAccount_COSMOSDB', 8 | }); 9 | 10 | app.storageQueue('storageQueueTrigger1', { 11 | queueName: 'inputqueue', 12 | connection: 'MyStorageConnectionAppSetting', 13 | return: cosmosOutput, 14 | handler: (queueItem, context) => { 15 | return { 16 | id: `${queueItem.name}-${queueItem.employeeId}`, 17 | name: queueItem.name, 18 | employeeId: queueItem.employeeId, 19 | address: queueItem.address, 20 | }; 21 | }, 22 | }); 23 | -------------------------------------------------------------------------------- /js/src/functions/cosmosOutput2.js: -------------------------------------------------------------------------------- 1 | const { app, output } = require('@azure/functions'); 2 | 3 | const cosmosOutput = output.cosmosDB({ 4 | databaseName: 'MyDatabase', 5 | collectionName: 'MyCollection', 6 | createIfNotExists: true, 7 | connectionStringSetting: 'MyAccount_COSMOSDB', 8 | }); 9 | 10 | app.storageQueue('storageQueueTrigger1', { 11 | queueName: 'inputqueue', 12 | connection: 'MyStorageConnectionAppSetting', 13 | return: cosmosOutput, 14 | handler: (queueItem, context) => { 15 | // 16 | return [ 17 | { 18 | id: 'John Henry-123456', 19 | name: 'John Henry', 20 | employeeId: '123456', 21 | address: 'A town nearby', 22 | }, 23 | { 24 | id: 'John Doe-123457', 25 | name: 'John Doe', 26 | employeeId: '123457', 27 | address: 'A town far away', 28 | }, 29 | ]; 30 | // 31 | }, 32 | }); 33 | -------------------------------------------------------------------------------- /js/src/functions/eventGridOutput1.js: -------------------------------------------------------------------------------- 1 | const { app, output } = require('@azure/functions'); 2 | 3 | const eventGridOutput = output.eventGrid({ 4 | topicEndpointUri: 'MyEventGridTopicUriSetting', 5 | topicKeySetting: 'MyEventGridTopicKeySetting', 6 | }); 7 | 8 | app.timer('timerTrigger1', { 9 | schedule: '0 */5 * * * *', 10 | return: eventGridOutput, 11 | handler: (myTimer, context) => { 12 | const timeStamp = new Date().toISOString(); 13 | return { 14 | id: 'message-id', 15 | subject: 'subject-name', 16 | dataVersion: '1.0', 17 | eventType: 'event-type', 18 | data: { 19 | name: 'John Henry', 20 | }, 21 | eventTime: timeStamp, 22 | }; 23 | }, 24 | }); 25 | -------------------------------------------------------------------------------- /js/src/functions/eventGridOutput2.js: -------------------------------------------------------------------------------- 1 | const { app, output } = require('@azure/functions'); 2 | 3 | const eventGridOutput = output.eventGrid({ 4 | topicEndpointUri: 'MyEventGridTopicUriSetting', 5 | topicKeySetting: 'MyEventGridTopicKeySetting', 6 | }); 7 | 8 | app.timer('timerTrigger1', { 9 | schedule: '0 */5 * * * *', 10 | return: eventGridOutput, 11 | handler: (myTimer, context) => { 12 | // 13 | const timeStamp = new Date().toISOString(); 14 | return [ 15 | { 16 | id: 'message-id', 17 | subject: 'subject-name', 18 | dataVersion: '1.0', 19 | eventType: 'event-type', 20 | data: { 21 | name: 'John Henry', 22 | }, 23 | eventTime: timeStamp, 24 | }, 25 | { 26 | id: 'message-id-2', 27 | subject: 'subject-name', 28 | dataVersion: '1.0', 29 | eventType: 'event-type', 30 | data: { 31 | name: 'John Doe', 32 | }, 33 | eventTime: timeStamp, 34 | }, 35 | ]; 36 | // 37 | }, 38 | }); 39 | -------------------------------------------------------------------------------- /js/src/functions/eventGridTrigger1.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | 3 | app.eventGrid('eventGridTrigger1', { 4 | handler: (event, context) => { 5 | context.log('Event grid function processed event:', event); 6 | }, 7 | }); 8 | -------------------------------------------------------------------------------- /js/src/functions/eventHubOutput1.js: -------------------------------------------------------------------------------- 1 | const { app, output } = require('@azure/functions'); 2 | 3 | const eventHubOutput = output.eventHub({ 4 | eventHubName: 'myeventhub', 5 | connection: 'MyEventHubSendAppSetting', 6 | }); 7 | 8 | app.timer('timerTrigger1', { 9 | schedule: '0 */5 * * * *', 10 | return: eventHubOutput, 11 | handler: (myTimer, context) => { 12 | const timeStamp = new Date().toISOString(); 13 | return `Message created at: ${timeStamp}`; 14 | }, 15 | }); 16 | -------------------------------------------------------------------------------- /js/src/functions/eventHubOutput2.js: -------------------------------------------------------------------------------- 1 | const { app, output } = require('@azure/functions'); 2 | 3 | const eventHubOutput = output.eventHub({ 4 | eventHubName: 'myeventhub', 5 | connection: 'MyEventHubSendAppSetting', 6 | }); 7 | 8 | app.timer('timerTrigger1', { 9 | schedule: '0 */5 * * * *', 10 | return: eventHubOutput, 11 | handler: (myTimer, context) => { 12 | // 13 | const timeStamp = new Date().toISOString(); 14 | const message = `Message created at: ${timeStamp}`; 15 | return [`1: ${message}`, `2: ${message}`]; 16 | // 17 | }, 18 | }); 19 | -------------------------------------------------------------------------------- /js/src/functions/eventHubTrigger1.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | 3 | app.eventHub('eventHubTrigger1', { 4 | connection: 'myEventHubReadConnectionAppSetting', 5 | eventHubName: 'MyEventHub', 6 | cardinality: 'one', 7 | handler: (message, context) => { 8 | context.log('Event hub function processed message:', message); 9 | context.log('EnqueuedTimeUtc =', context.triggerMetadata.enqueuedTimeUtc); 10 | context.log('SequenceNumber =', context.triggerMetadata.sequenceNumber); 11 | context.log('Offset =', context.triggerMetadata.offset); 12 | }, 13 | }); 14 | -------------------------------------------------------------------------------- /js/src/functions/eventHubTrigger2.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | 3 | app.eventHub('eventHubTrigger1', { 4 | connection: 'myEventHubReadConnectionAppSetting', 5 | eventHubName: 'MyEventHub', 6 | cardinality: 'many', 7 | handler: (messages, context) => { 8 | context.log(`Event hub function processed ${messages.length} messages`); 9 | for (let i = 0; i < messages.length; i++) { 10 | context.log('Event hub message:', messages[i]); 11 | context.log(`EnqueuedTimeUtc = ${context.triggerMetadata.enqueuedTimeUtcArray[i]}`); 12 | context.log(`SequenceNumber = ${context.triggerMetadata.sequenceNumberArray[i]}`); 13 | context.log(`Offset = ${context.triggerMetadata.offsetArray[i]}`); 14 | } 15 | }, 16 | }); 17 | -------------------------------------------------------------------------------- /js/src/functions/httpTrigger1.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | 3 | app.http('httpTrigger1', { 4 | methods: ['GET', 'POST'], 5 | authLevel: 'anonymous', 6 | handler: async (request, context) => { 7 | context.log(`Http function processed request for url "${request.url}"`); 8 | 9 | const name = request.query.get('name') || (await request.text()) || 'world'; 10 | 11 | return { body: `Hello, ${name}!` }; 12 | }, 13 | }); 14 | -------------------------------------------------------------------------------- /js/src/functions/httpTrigger2.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | 3 | app.http('httpTrigger1', { 4 | methods: ['GET'], 5 | authLevel: 'anonymous', 6 | route: 'products/{category:alpha}/{id:int?}', 7 | handler: async (request, context) => { 8 | const category = request.params.category; 9 | const id = request.params.id; 10 | 11 | return { body: `Category: ${category}, ID: ${id}` }; 12 | }, 13 | }); 14 | -------------------------------------------------------------------------------- /js/src/functions/httpTrigger3.js: -------------------------------------------------------------------------------- 1 | const { app, input } = require('@azure/functions'); 2 | 3 | const tableInput = input.table({ 4 | connection: 'MyStorageConnectionAppSetting', 5 | partitionKey: 'products', 6 | tableName: 'products', 7 | rowKey: '{id}', 8 | }); 9 | 10 | app.http('httpTrigger1', { 11 | methods: ['GET'], 12 | authLevel: 'anonymous', 13 | route: 'products/{id}', 14 | extraInputs: [tableInput], 15 | handler: async (request, context) => { 16 | return { jsonBody: context.extraInputs.get(tableInput) }; 17 | }, 18 | }); 19 | -------------------------------------------------------------------------------- /js/src/functions/httpTriggerBadAsync.js: -------------------------------------------------------------------------------- 1 | // DO NOT USE THIS CODE 2 | const { app } = require('@azure/functions'); 3 | const fs = require('fs'); 4 | 5 | app.http('httpTriggerBadAsync', { 6 | methods: ['GET', 'POST'], 7 | authLevel: 'anonymous', 8 | handler: async (request, context) => { 9 | let fileData; 10 | fs.readFile('./helloWorld.txt', (err, data) => { 11 | if (err) { 12 | context.error(err); 13 | // BUG #1: This will result in an uncaught exception that crashes the entire process 14 | throw err; 15 | } 16 | fileData = data; 17 | }); 18 | // BUG #2: fileData is not guaranteed to be set before the invocation ends 19 | return { body: fileData }; 20 | }, 21 | }); 22 | -------------------------------------------------------------------------------- /js/src/functions/httpTriggerGoodAsync.js: -------------------------------------------------------------------------------- 1 | // Recommended pattern 2 | const { app } = require('@azure/functions'); 3 | const fs = require('fs/promises'); 4 | 5 | app.http('httpTriggerGoodAsync', { 6 | methods: ['GET', 'POST'], 7 | authLevel: 'anonymous', 8 | handler: async (request, context) => { 9 | try { 10 | const fileData = await fs.readFile('./helloWorld.txt'); 11 | return { body: fileData }; 12 | } catch (err) { 13 | context.error(err); 14 | // This rethrown exception will only fail the individual invocation, instead of crashing the whole process 15 | throw err; 16 | } 17 | }, 18 | }); 19 | -------------------------------------------------------------------------------- /js/src/functions/httpTriggerStreamRequest.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | const { createWriteStream } = require('fs'); 3 | const { Writable } = require('stream'); 4 | 5 | app.http('httpTriggerStreamRequest', { 6 | methods: ['POST'], 7 | authLevel: 'anonymous', 8 | handler: async (request, context) => { 9 | const writeStream = createWriteStream(''); 10 | await request.body.pipeTo(Writable.toWeb(writeStream)); 11 | 12 | return { body: 'Done!' }; 13 | }, 14 | }); 15 | -------------------------------------------------------------------------------- /js/src/functions/httpTriggerStreamResponse.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | const { createReadStream } = require('fs'); 3 | 4 | app.http('httpTriggerStreamResponse', { 5 | methods: ['GET'], 6 | authLevel: 'anonymous', 7 | handler: async (request, context) => { 8 | const body = createReadStream(''); 9 | 10 | return { body }; 11 | }, 12 | }); 13 | -------------------------------------------------------------------------------- /js/src/functions/serviceBusOutput1.js: -------------------------------------------------------------------------------- 1 | const { app, output } = require('@azure/functions'); 2 | 3 | const serviceBusOutput = output.serviceBusQueue({ 4 | queueName: 'testqueue', 5 | connection: 'MyServiceBusConnection', 6 | }); 7 | 8 | app.timer('timerTrigger1', { 9 | schedule: '0 */5 * * * *', 10 | return: serviceBusOutput, 11 | handler: (myTimer, context) => { 12 | const timeStamp = new Date().toISOString(); 13 | return `Message created at: ${timeStamp}`; 14 | }, 15 | }); 16 | -------------------------------------------------------------------------------- /js/src/functions/serviceBusOutput2.js: -------------------------------------------------------------------------------- 1 | const { app, output } = require('@azure/functions'); 2 | 3 | const serviceBusOutput = output.serviceBusQueue({ 4 | queueName: 'testqueue', 5 | connection: 'MyServiceBusConnection', 6 | }); 7 | 8 | app.timer('timerTrigger1', { 9 | schedule: '0 */5 * * * *', 10 | return: serviceBusOutput, 11 | handler: (myTimer, context) => { 12 | // 13 | const timeStamp = new Date().toISOString(); 14 | const message = `Message created at: ${timeStamp}`; 15 | return [`1: ${message}`, `2: ${message}`]; 16 | // 17 | }, 18 | }); 19 | -------------------------------------------------------------------------------- /js/src/functions/serviceBusTrigger1.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | 3 | app.serviceBusQueue('serviceBusQueueTrigger1', { 4 | connection: 'MyServiceBusConnection', 5 | queueName: 'testqueue', 6 | handler: (message, context) => { 7 | context.log('Service bus queue function processed message:', message); 8 | context.log('EnqueuedTimeUtc =', context.triggerMetadata.enqueuedTimeUtc); 9 | context.log('DeliveryCount =', context.triggerMetadata.deliveryCount); 10 | context.log('MessageId =', context.triggerMetadata.messageId); 11 | }, 12 | }); 13 | -------------------------------------------------------------------------------- /js/src/functions/sqlInput1.js: -------------------------------------------------------------------------------- 1 | const { app, input } = require('@azure/functions'); 2 | 3 | const sqlInput = input.sql({ 4 | commandText: 'select [Id], [order], [title], [url], [completed] from dbo.ToDo', 5 | commandType: 'Text', 6 | connectionStringSetting: 'SqlConnectionString', 7 | }); 8 | 9 | app.http('httpTrigger1', { 10 | methods: ['GET'], 11 | authLevel: 'anonymous', 12 | extraInputs: [sqlInput], 13 | handler: (request, context) => { 14 | context.log('HTTP trigger and SQL input binding function processed a request.'); 15 | const toDoItems = context.extraInputs.get(sqlInput); 16 | return { 17 | jsonBody: toDoItems, 18 | }; 19 | }, 20 | }); 21 | -------------------------------------------------------------------------------- /js/src/functions/sqlInput2.js: -------------------------------------------------------------------------------- 1 | const { app, input } = require('@azure/functions'); 2 | 3 | const sqlInput = input.sql({ 4 | commandText: 'select [Id], [order], [title], [url], [completed] from dbo.ToDo where Id = @Id', 5 | commandType: 'Text', 6 | parameters: '@Id={Query.id}', 7 | connectionStringSetting: 'SqlConnectionString', 8 | }); 9 | 10 | app.http('httpTrigger1', { 11 | methods: ['GET'], 12 | authLevel: 'anonymous', 13 | extraInputs: [sqlInput], 14 | handler: (request, context) => { 15 | context.log('HTTP trigger and SQL input binding function processed a request.'); 16 | const toDoItem = context.extraInputs.get(sqlInput); 17 | return { 18 | jsonBody: toDoItem, 19 | }; 20 | }, 21 | }); 22 | -------------------------------------------------------------------------------- /js/src/functions/sqlInput3.js: -------------------------------------------------------------------------------- 1 | const { app, input } = require('@azure/functions'); 2 | 3 | const sqlInput = input.sql({ 4 | commandText: 'DeleteToDo', 5 | commandType: 'StoredProcedure', 6 | parameters: '@Id={Query.id}', 7 | connectionStringSetting: 'SqlConnectionString', 8 | }); 9 | 10 | app.http('httpTrigger1', { 11 | methods: ['GET'], 12 | authLevel: 'anonymous', 13 | extraInputs: [sqlInput], 14 | handler: (request, context) => { 15 | context.log('HTTP trigger and SQL input binding function processed a request.'); 16 | const toDoItems = context.extraInputs.get(sqlInput); 17 | return { 18 | jsonBody: toDoItems, 19 | }; 20 | }, 21 | }); 22 | -------------------------------------------------------------------------------- /js/src/functions/sqlOutput1.js: -------------------------------------------------------------------------------- 1 | const { app, output } = require('@azure/functions'); 2 | 3 | const sqlOutput = output.sql({ 4 | commandText: 'dbo.ToDo', 5 | connectionStringSetting: 'SqlConnectionString', 6 | }); 7 | 8 | app.http('httpTrigger1', { 9 | methods: ['POST'], 10 | authLevel: 'anonymous', 11 | extraOutputs: [sqlOutput], 12 | handler: async (request, context) => { 13 | context.log('HTTP trigger and SQL output binding function processed a request.'); 14 | 15 | const body = await request.json(); 16 | context.extraOutputs.set(sqlOutput, body); 17 | return { status: 201 }; 18 | }, 19 | }); 20 | -------------------------------------------------------------------------------- /js/src/functions/sqlOutput2.js: -------------------------------------------------------------------------------- 1 | const { app, output } = require('@azure/functions'); 2 | 3 | const sqlTodoOutput = output.sql({ 4 | commandText: 'dbo.ToDo', 5 | connectionStringSetting: 'SqlConnectionString', 6 | }); 7 | 8 | const sqlRequestLogOutput = output.sql({ 9 | commandText: 'dbo.RequestLog', 10 | connectionStringSetting: 'SqlConnectionString', 11 | }); 12 | 13 | app.http('httpTrigger1', { 14 | methods: ['POST'], 15 | authLevel: 'anonymous', 16 | extraOutputs: [sqlTodoOutput, sqlRequestLogOutput], 17 | handler: async (request, context) => { 18 | context.log('HTTP trigger and SQL output binding function processed a request.'); 19 | 20 | const newLog = { 21 | RequestTimeStamp: Date.now(), 22 | ItemCount: 1, 23 | }; 24 | context.extraOutputs.set(sqlRequestLogOutput, newLog); 25 | 26 | const body = await request.json(); 27 | context.extraOutputs.set(sqlTodoOutput, body); 28 | 29 | return { status: 201 }; 30 | }, 31 | }); 32 | -------------------------------------------------------------------------------- /js/src/functions/storageBlobInputAndOutput1.js: -------------------------------------------------------------------------------- 1 | const { app, input, output } = require('@azure/functions'); 2 | 3 | const blobInput = input.storageBlob({ 4 | path: 'samples-workitems/{queueTrigger}', 5 | connection: 'MyStorageConnectionAppSetting', 6 | }); 7 | 8 | const blobOutput = output.storageBlob({ 9 | path: 'samples-workitems/{queueTrigger}-Copy', 10 | connection: 'MyStorageConnectionAppSetting', 11 | }); 12 | 13 | app.storageQueue('storageQueueTrigger1', { 14 | queueName: 'myqueue-items', 15 | connection: 'MyStorageConnectionAppSetting', 16 | extraInputs: [blobInput], 17 | return: blobOutput, 18 | handler: (queueItem, context) => { 19 | return context.extraInputs.get(blobInput); 20 | }, 21 | }); 22 | -------------------------------------------------------------------------------- /js/src/functions/storageBlobTrigger1.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | 3 | app.storageBlob('storageBlobTrigger1', { 4 | path: 'samples-workitems/{name}', 5 | connection: 'MyStorageAccountAppSetting', 6 | handler: (blob, context) => { 7 | context.log( 8 | `Storage blob function processed blob "${context.triggerMetadata.name}" with size ${blob.length} bytes` 9 | ); 10 | }, 11 | }); 12 | -------------------------------------------------------------------------------- /js/src/functions/storageBlobTrigger2.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | 3 | app.storageBlob('storageBlobTrigger1', { 4 | path: 'samples-workitems/{name}', 5 | connection: 'MyStorageAccountAppSetting', 6 | handler: (blob, context) => { 7 | context.log( 8 | `Storage blob function processed blob "${context.triggerMetadata.name}" with size ${blob.length} bytes` 9 | ); 10 | }, 11 | }); 12 | -------------------------------------------------------------------------------- /js/src/functions/storageBlobTriggerEventGrid1.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | 3 | app.storageBlob('storageBlobTrigger1', { 4 | path: 'samples-workitems/{name}', 5 | connection: 'MyStorageAccountAppSetting', 6 | source: 'EventGrid', 7 | handler: (blob, context) => { 8 | context.log( 9 | `Storage blob function processed blob "${context.triggerMetadata.name}" with size ${blob.length} bytes` 10 | ); 11 | }, 12 | }); 13 | -------------------------------------------------------------------------------- /js/src/functions/storageQueueOutput1.js: -------------------------------------------------------------------------------- 1 | const { app, output } = require('@azure/functions'); 2 | 3 | const queueOutput = output.storageQueue({ 4 | queueName: 'outqueue', 5 | connection: 'MyStorageConnectionAppSetting', 6 | }); 7 | 8 | app.http('httpTrigger1', { 9 | methods: ['GET', 'POST'], 10 | authLevel: 'anonymous', 11 | extraOutputs: [queueOutput], 12 | handler: async (request, context) => { 13 | const body = await request.text(); 14 | context.extraOutputs.set(queueOutput, body); 15 | return { body: 'Created queue item.' }; 16 | }, 17 | }); 18 | -------------------------------------------------------------------------------- /js/src/functions/storageQueueOutput2.js: -------------------------------------------------------------------------------- 1 | const { app, output } = require('@azure/functions'); 2 | 3 | const queueOutput = output.storageQueue({ 4 | queueName: 'outqueue', 5 | connection: 'MyStorageConnectionAppSetting', 6 | }); 7 | 8 | app.http('httpTrigger1', { 9 | methods: ['GET', 'POST'], 10 | authLevel: 'anonymous', 11 | extraOutputs: [queueOutput], 12 | handler: async (request, context) => { 13 | // 14 | context.extraOutputs.set(queueOutput, ['message 1', 'message 2']); 15 | // 16 | return { body: 'Created queue item.' }; 17 | }, 18 | }); 19 | -------------------------------------------------------------------------------- /js/src/functions/storageQueueTrigger1.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | 3 | app.storageQueue('storageQueueTrigger1', { 4 | queueName: 'myqueue-items', 5 | connection: 'MyStorageConnectionAppSetting', 6 | handler: (queueItem, context) => { 7 | context.log('Storage queue function processed work item:', queueItem); 8 | context.log('expirationTime =', context.triggerMetadata.expirationTime); 9 | context.log('insertionTime =', context.triggerMetadata.insertionTime); 10 | context.log('nextVisibleTime =', context.triggerMetadata.nextVisibleTime); 11 | context.log('id =', context.triggerMetadata.id); 12 | context.log('popReceipt =', context.triggerMetadata.popReceipt); 13 | context.log('dequeueCount =', context.triggerMetadata.dequeueCount); 14 | }, 15 | }); 16 | -------------------------------------------------------------------------------- /js/src/functions/tableInput1.js: -------------------------------------------------------------------------------- 1 | const { app, input } = require('@azure/functions'); 2 | 3 | const tableInput = input.table({ 4 | tableName: 'Person', 5 | partitionKey: 'Test', 6 | rowKey: '{queueTrigger}', 7 | connection: 'MyStorageConnectionAppSetting', 8 | }); 9 | 10 | app.storageQueue('storageQueueTrigger1', { 11 | queueName: 'myqueue-items', 12 | connection: 'MyStorageConnectionAppSetting', 13 | extraInputs: [tableInput], 14 | handler: (queueItem, context) => { 15 | context.log('Node.js queue trigger function processed work item', queueItem); 16 | const person = context.extraInputs.get(tableInput); 17 | context.log('Person entity name: ' + person.Name); 18 | }, 19 | }); 20 | -------------------------------------------------------------------------------- /js/src/functions/tableOutput1.js: -------------------------------------------------------------------------------- 1 | const { app, output } = require('@azure/functions'); 2 | 3 | const tableOutput = output.table({ 4 | tableName: 'Person', 5 | connection: 'MyStorageConnectionAppSetting', 6 | }); 7 | 8 | app.http('httpTrigger1', { 9 | methods: ['POST'], 10 | authLevel: 'anonymous', 11 | extraOutputs: [tableOutput], 12 | handler: async (request, context) => { 13 | const rows = []; 14 | for (let i = 1; i < 10; i++) { 15 | rows.push({ 16 | PartitionKey: 'Test', 17 | RowKey: i.toString(), 18 | Name: `Name ${i}`, 19 | }); 20 | } 21 | context.extraOutputs.set(tableOutput, rows); 22 | return { status: 201 }; 23 | }, 24 | }); 25 | -------------------------------------------------------------------------------- /js/src/functions/timerTrigger1.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | 3 | app.timer('timerTrigger1', { 4 | schedule: '0 */5 * * * *', 5 | handler: (myTimer, context) => { 6 | context.log('Timer function processed request.'); 7 | }, 8 | }); 9 | -------------------------------------------------------------------------------- /js/src/functions/timerTriggerWithRetry.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | 3 | app.timer('timerTriggerWithRetry', { 4 | schedule: '0 */5 * * * *', 5 | retry: { 6 | strategy: 'fixedDelay', 7 | delayInterval: { 8 | seconds: 10, 9 | }, 10 | maxRetryCount: 4, 11 | }, 12 | handler: (myTimer, context) => { 13 | if (context.retryContext?.retryCount < 2) { 14 | throw new Error('Retry!'); 15 | } else { 16 | context.log('Timer function processed request.'); 17 | } 18 | }, 19 | }); 20 | -------------------------------------------------------------------------------- /js/src/functions/warmupTrigger.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | 3 | app.warmup('warmupTrigger', { 4 | handler: (warmupContext, context) => { 5 | context.log('Function App instance is warm.'); 6 | }, 7 | }); 8 | -------------------------------------------------------------------------------- /js/src/invocationHooks1.js: -------------------------------------------------------------------------------- 1 | const { app } = require('@azure/functions'); 2 | 3 | app.hook.preInvocation((context) => { 4 | if (context.invocationContext.options.trigger.type === 'httpTrigger') { 5 | context.invocationContext.log( 6 | `preInvocation hook executed for http function ${context.invocationContext.functionName}` 7 | ); 8 | } 9 | }); 10 | 11 | app.hook.postInvocation((context) => { 12 | if (context.invocationContext.options.trigger.type === 'httpTrigger') { 13 | context.invocationContext.log( 14 | `postInvocation hook executed for http function ${context.invocationContext.functionName}` 15 | ); 16 | } 17 | }); 18 | -------------------------------------------------------------------------------- /js/src/otelAppInsights.js: -------------------------------------------------------------------------------- 1 | const { AzureFunctionsInstrumentation } = require('@azure/functions-opentelemetry-instrumentation'); 2 | const { AzureMonitorLogExporter, AzureMonitorTraceExporter } = require('@azure/monitor-opentelemetry-exporter'); 3 | const { getNodeAutoInstrumentations, getResourceDetectors } = require('@opentelemetry/auto-instrumentations-node'); 4 | const { registerInstrumentations } = require('@opentelemetry/instrumentation'); 5 | const { detectResourcesSync } = require('@opentelemetry/resources'); 6 | const { LoggerProvider, SimpleLogRecordProcessor } = require('@opentelemetry/sdk-logs'); 7 | const { NodeTracerProvider, SimpleSpanProcessor } = require('@opentelemetry/sdk-trace-node'); 8 | 9 | const resource = detectResourcesSync({ detectors: getResourceDetectors() }); 10 | 11 | const tracerProvider = new NodeTracerProvider({ resource }); 12 | tracerProvider.addSpanProcessor(new SimpleSpanProcessor(new AzureMonitorTraceExporter())); 13 | tracerProvider.register(); 14 | 15 | const loggerProvider = new LoggerProvider({ resource }); 16 | loggerProvider.addLogRecordProcessor(new SimpleLogRecordProcessor(new AzureMonitorLogExporter())); 17 | 18 | registerInstrumentations({ 19 | tracerProvider, 20 | loggerProvider, 21 | instrumentations: [getNodeAutoInstrumentations(), new AzureFunctionsInstrumentation()], 22 | }); 23 | -------------------------------------------------------------------------------- /js/src/otelOtlp.js: -------------------------------------------------------------------------------- 1 | const { AzureFunctionsInstrumentation } = require('@azure/functions-opentelemetry-instrumentation'); 2 | const { getNodeAutoInstrumentations, getResourceDetectors } = require('@opentelemetry/auto-instrumentations-node'); 3 | const { OTLPLogExporter } = require('@opentelemetry/exporter-logs-otlp-http'); 4 | const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-http'); 5 | const { registerInstrumentations } = require('@opentelemetry/instrumentation'); 6 | const { detectResourcesSync } = require('@opentelemetry/resources'); 7 | const { LoggerProvider, SimpleLogRecordProcessor } = require('@opentelemetry/sdk-logs'); 8 | const { NodeTracerProvider, SimpleSpanProcessor } = require('@opentelemetry/sdk-trace-node'); 9 | 10 | const resource = detectResourcesSync({ detectors: getResourceDetectors() }); 11 | 12 | const tracerProvider = new NodeTracerProvider({ resource }); 13 | tracerProvider.addSpanProcessor(new SimpleSpanProcessor(new OTLPTraceExporter())); 14 | tracerProvider.register(); 15 | 16 | const loggerProvider = new LoggerProvider({ resource }); 17 | loggerProvider.addLogRecordProcessor(new SimpleLogRecordProcessor(new OTLPLogExporter())); 18 | 19 | registerInstrumentations({ 20 | tracerProvider, 21 | loggerProvider, 22 | instrumentations: [getNodeAutoInstrumentations(), new AzureFunctionsInstrumentation()], 23 | }); 24 | -------------------------------------------------------------------------------- /ts/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "@typescript-eslint/parser", 3 | "plugins": ["@typescript-eslint", "deprecation", "simple-import-sort", "import"], 4 | "parserOptions": { 5 | "project": "tsconfig.json", 6 | "sourceType": "module" 7 | }, 8 | "extends": [ 9 | "eslint:recommended", 10 | "plugin:@typescript-eslint/recommended", 11 | "plugin:@typescript-eslint/recommended-requiring-type-checking", 12 | "plugin:prettier/recommended" 13 | ], 14 | "rules": { 15 | "deprecation/deprecation": "error", 16 | "@typescript-eslint/no-empty-interface": "off", 17 | "@typescript-eslint/no-explicit-any": "off", 18 | "@typescript-eslint/no-namespace": "off", 19 | "@typescript-eslint/no-unused-vars": "off", 20 | "prefer-const": ["error", { "destructuring": "all" }], 21 | "@typescript-eslint/explicit-member-accessibility": [ 22 | "error", 23 | { 24 | "accessibility": "no-public" 25 | } 26 | ], 27 | "no-return-await": "off", 28 | "@typescript-eslint/return-await": "error", 29 | "eqeqeq": "error", 30 | "@typescript-eslint/require-await": "off", 31 | "@typescript-eslint/restrict-template-expressions": "off", 32 | "simple-import-sort/imports": [ 33 | "error", 34 | { 35 | "groups": [["^\\u0000", "^node:", "^@?\\w", "^", "^\\."]] 36 | } 37 | ], 38 | "simple-import-sort/exports": "error", 39 | "import/first": "error", 40 | "import/newline-after-import": "error", 41 | "import/no-duplicates": "error" 42 | }, 43 | "ignorePatterns": ["**/*.js", "**/*.mjs", "**/*.cjs", "out", "dist"] 44 | } 45 | -------------------------------------------------------------------------------- /ts/.funcignore: -------------------------------------------------------------------------------- 1 | *.js.map 2 | *.ts 3 | .git* 4 | .vscode 5 | __azurite_db*__.json 6 | __blobstorage__ 7 | __queuestorage__ 8 | local.settings.json 9 | test 10 | tsconfig.json -------------------------------------------------------------------------------- /ts/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | 24 | # nyc test coverage 25 | .nyc_output 26 | 27 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 28 | .grunt 29 | 30 | # Bower dependency directory (https://bower.io/) 31 | bower_components 32 | 33 | # node-waf configuration 34 | .lock-wscript 35 | 36 | # Compiled binary addons (https://nodejs.org/api/addons.html) 37 | build/Release 38 | 39 | # Dependency directories 40 | node_modules/ 41 | jspm_packages/ 42 | 43 | # TypeScript v1 declaration files 44 | typings/ 45 | 46 | # Optional npm cache directory 47 | .npm 48 | 49 | # Optional eslint cache 50 | .eslintcache 51 | 52 | # Optional REPL history 53 | .node_repl_history 54 | 55 | # Output of 'npm pack' 56 | *.tgz 57 | 58 | # Yarn Integrity file 59 | .yarn-integrity 60 | 61 | # dotenv environment variables file 62 | .env 63 | .env.test 64 | 65 | # parcel-bundler cache (https://parceljs.org/) 66 | .cache 67 | 68 | # next.js build output 69 | .next 70 | 71 | # nuxt.js build output 72 | .nuxt 73 | 74 | # vuepress build output 75 | .vuepress/dist 76 | 77 | # Serverless directories 78 | .serverless/ 79 | 80 | # FuseBox cache 81 | .fusebox/ 82 | 83 | # DynamoDB Local files 84 | .dynamodb/ 85 | 86 | # TypeScript output 87 | dist 88 | out 89 | 90 | # Azure Functions artifacts 91 | bin 92 | obj 93 | appsettings.json 94 | local.settings.json 95 | 96 | # Azurite artifacts 97 | __blobstorage__ 98 | __queuestorage__ 99 | __azurite_db*__.json -------------------------------------------------------------------------------- /ts/.prettierignore: -------------------------------------------------------------------------------- 1 | out 2 | dist 3 | node_modules 4 | 5 | # Exclude markdown until this bug is fixed: https://github.com/prettier/prettier/issues/5019 6 | *.md -------------------------------------------------------------------------------- /ts/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 4, 3 | "singleQuote": true, 4 | "printWidth": 120, 5 | "endOfLine": "auto" 6 | } 7 | -------------------------------------------------------------------------------- /ts/.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": ["ms-azuretools.vscode-azurefunctions", "dbaeumer.vscode-eslint", "esbenp.prettier-vscode"] 3 | } 4 | -------------------------------------------------------------------------------- /ts/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Attach to Node Functions", 6 | "type": "node", 7 | "request": "attach", 8 | "port": 9229, 9 | "preLaunchTask": "func: host start" 10 | } 11 | ] 12 | } 13 | -------------------------------------------------------------------------------- /ts/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "azureFunctions.deploySubpath": ".", 3 | "azureFunctions.postDeployTask": "npm install (functions)", 4 | "azureFunctions.projectLanguage": "TypeScript", 5 | "azureFunctions.projectRuntime": "~4", 6 | "debug.internalConsoleOptions": "neverOpen", 7 | "azureFunctions.projectLanguageModel": 4, 8 | "azureFunctions.preDeployTask": "npm prune (functions)", 9 | "editor.codeActionsOnSave": ["source.fixAll"], 10 | "editor.formatOnSave": true, 11 | "editor.defaultFormatter": "esbenp.prettier-vscode" 12 | } 13 | -------------------------------------------------------------------------------- /ts/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "type": "func", 6 | "label": "func: host start", 7 | "command": "host start", 8 | "problemMatcher": "$func-node-watch", 9 | "isBackground": true, 10 | "dependsOn": "npm build (functions)" 11 | }, 12 | { 13 | "type": "shell", 14 | "label": "npm build (functions)", 15 | "command": "npm run build", 16 | "dependsOn": "npm clean (functions)", 17 | "problemMatcher": "$tsc" 18 | }, 19 | { 20 | "type": "shell", 21 | "label": "npm install (functions)", 22 | "command": "npm install" 23 | }, 24 | { 25 | "type": "shell", 26 | "label": "npm prune (functions)", 27 | "command": "npm prune --production", 28 | "dependsOn": "npm build (functions)", 29 | "problemMatcher": [] 30 | }, 31 | { 32 | "type": "shell", 33 | "label": "npm clean (functions)", 34 | "command": "npm run clean", 35 | "dependsOn": "npm install (functions)" 36 | } 37 | ] 38 | } 39 | -------------------------------------------------------------------------------- /ts/host.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0", 3 | "logging": { 4 | "applicationInsights": { 5 | "samplingSettings": { 6 | "isEnabled": true, 7 | "excludedTypes": "Request" 8 | } 9 | } 10 | }, 11 | "extensionBundle": { 12 | "id": "Microsoft.Azure.Functions.ExtensionBundle", 13 | "version": "[3.15.0, 4.0.0)" 14 | }, 15 | "concurrency": { 16 | "dynamicConcurrencyEnabled": true, 17 | "snapshotPersistenceEnabled": true 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /ts/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "triggerdocsts", 3 | "version": "1.0.0", 4 | "description": "", 5 | "scripts": { 6 | "build": "tsc", 7 | "lint": "eslint . --fix", 8 | "format": "prettier . --write", 9 | "watch": "tsc -w", 10 | "clean": "rimraf dist", 11 | "prestart": "npm run clean && npm run build", 12 | "start": "func start", 13 | "test": "echo \"No tests yet...\"" 14 | }, 15 | "dependencies": { 16 | "@azure/functions": "^4.5.0", 17 | "@azure/functions-opentelemetry-instrumentation": "^0.1.0", 18 | "@azure/monitor-opentelemetry-exporter": "^1.0.0-beta.23", 19 | "@opentelemetry/api": "^1.8.0", 20 | "@opentelemetry/auto-instrumentations-node": "^0.46.1", 21 | "@opentelemetry/exporter-logs-otlp-http": "^0.51.1" 22 | }, 23 | "devDependencies": { 24 | "@types/node": "^18.x", 25 | "@typescript-eslint/eslint-plugin": "^5.12.1", 26 | "@typescript-eslint/parser": "^5.12.1", 27 | "eslint": "^7.32.0", 28 | "eslint-config-prettier": "^8.3.0", 29 | "eslint-plugin-deprecation": "^1.3.2", 30 | "eslint-plugin-import": "^2.29.0", 31 | "eslint-plugin-prettier": "^4.0.0", 32 | "eslint-plugin-simple-import-sort": "^10.0.0", 33 | "prettier": "^2.4.1", 34 | "rimraf": "^5.0.0", 35 | "typescript": "^4.0.0" 36 | }, 37 | "main": "dist/src/functions/*.js" 38 | } 39 | -------------------------------------------------------------------------------- /ts/src/appHooks1.ts: -------------------------------------------------------------------------------- 1 | import { app, AppStartContext, AppTerminateContext } from '@azure/functions'; 2 | 3 | app.hook.appStart((context: AppStartContext) => { 4 | // add your logic here 5 | }); 6 | 7 | app.hook.appTerminate((context: AppTerminateContext) => { 8 | // add your logic here 9 | }); 10 | -------------------------------------------------------------------------------- /ts/src/functions/cosmosDBTrigger1.ts: -------------------------------------------------------------------------------- 1 | import { app, InvocationContext } from '@azure/functions'; 2 | 3 | export async function cosmosDBTrigger1(documents: unknown[], context: InvocationContext): Promise { 4 | context.log(`Cosmos DB function processed ${documents.length} documents`); 5 | } 6 | 7 | app.cosmosDB('cosmosDBTrigger1', { 8 | connection: '', 9 | databaseName: 'Tasks', 10 | containerName: 'Items', 11 | createLeaseContainerIfNotExists: true, 12 | handler: cosmosDBTrigger1, 13 | }); 14 | -------------------------------------------------------------------------------- /ts/src/functions/cosmosInput1.ts: -------------------------------------------------------------------------------- 1 | import { app, input, InvocationContext, output } from '@azure/functions'; 2 | 3 | const cosmosInput = input.cosmosDB({ 4 | databaseName: 'MyDatabase', 5 | collectionName: 'MyCollection', 6 | id: '{queueTrigger}', 7 | partitionKey: '{queueTrigger}', 8 | connectionStringSetting: 'MyAccount_COSMOSDB', 9 | }); 10 | 11 | const cosmosOutput = output.cosmosDB({ 12 | databaseName: 'MyDatabase', 13 | collectionName: 'MyCollection', 14 | createIfNotExists: false, 15 | partitionKey: '{queueTrigger}', 16 | connectionStringSetting: 'MyAccount_COSMOSDB', 17 | }); 18 | 19 | interface MyDocument { 20 | text: string; 21 | } 22 | 23 | export async function storageQueueTrigger1(queueItem: unknown, context: InvocationContext): Promise { 24 | const doc = context.extraInputs.get(cosmosInput); 25 | doc.text = 'This was updated!'; 26 | context.extraOutputs.set(cosmosOutput, doc); 27 | } 28 | 29 | app.storageQueue('storageQueueTrigger1', { 30 | queueName: 'outqueue', 31 | connection: 'MyStorageConnectionAppSetting', 32 | extraInputs: [cosmosInput], 33 | extraOutputs: [cosmosOutput], 34 | handler: storageQueueTrigger1, 35 | }); 36 | -------------------------------------------------------------------------------- /ts/src/functions/cosmosInput2.ts: -------------------------------------------------------------------------------- 1 | import { app, HttpRequest, HttpResponseInit, input, InvocationContext } from '@azure/functions'; 2 | 3 | const cosmosInput = input.cosmosDB({ 4 | databaseName: 'ToDoItems', 5 | collectionName: 'Items', 6 | id: '{Query.id}', 7 | partitionKey: '{Query.partitionKeyValue}', 8 | connectionStringSetting: 'CosmosDBConnection', 9 | }); 10 | 11 | interface ToDoDocument { 12 | description: string; 13 | } 14 | 15 | export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise { 16 | const toDoItem = context.extraInputs.get(cosmosInput); 17 | if (!toDoItem) { 18 | return { 19 | status: 404, 20 | body: 'ToDo item not found', 21 | }; 22 | } else { 23 | return { 24 | body: `Found ToDo item, Description=${toDoItem.description}`, 25 | }; 26 | } 27 | } 28 | 29 | app.http('httpTrigger1', { 30 | methods: ['GET', 'POST'], 31 | authLevel: 'anonymous', 32 | extraInputs: [cosmosInput], 33 | handler: httpTrigger1, 34 | }); 35 | -------------------------------------------------------------------------------- /ts/src/functions/cosmosInput3.ts: -------------------------------------------------------------------------------- 1 | import { app, HttpRequest, HttpResponseInit, input, InvocationContext } from '@azure/functions'; 2 | 3 | const cosmosInput = input.cosmosDB({ 4 | databaseName: 'ToDoItems', 5 | collectionName: 'Items', 6 | id: '{id}', 7 | partitionKey: '{partitionKeyValue}', 8 | connectionStringSetting: 'CosmosDBConnection', 9 | }); 10 | 11 | interface ToDoDocument { 12 | description: string; 13 | } 14 | 15 | export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise { 16 | const toDoItem = context.extraInputs.get(cosmosInput); 17 | if (!toDoItem) { 18 | return { 19 | status: 404, 20 | body: 'ToDo item not found', 21 | }; 22 | } else { 23 | return { 24 | body: `Found ToDo item, Description=${toDoItem.description}`, 25 | }; 26 | } 27 | } 28 | 29 | app.http('httpTrigger1', { 30 | methods: ['GET', 'POST'], 31 | authLevel: 'anonymous', 32 | route: 'todoitems/{partitionKeyValue}/{id}', 33 | extraInputs: [cosmosInput], 34 | handler: httpTrigger1, 35 | }); 36 | -------------------------------------------------------------------------------- /ts/src/functions/cosmosInput4.ts: -------------------------------------------------------------------------------- 1 | import { app, input, InvocationContext } from '@azure/functions'; 2 | 3 | const cosmosInput = input.cosmosDB({ 4 | databaseName: 'MyDb', 5 | collectionName: 'MyCollection', 6 | sqlQuery: 'SELECT * from c where c.departmentId = {departmentId}', 7 | connectionStringSetting: 'CosmosDBConnection', 8 | }); 9 | 10 | interface MyDocument {} 11 | 12 | export async function storageQueueTrigger1(queueItem: unknown, context: InvocationContext): Promise { 13 | const documents = context.extraInputs.get(cosmosInput); 14 | for (const document of documents) { 15 | // operate on each document 16 | } 17 | } 18 | 19 | app.storageQueue('storageQueueTrigger1', { 20 | queueName: 'outqueue', 21 | connection: 'MyStorageConnectionAppSetting', 22 | extraInputs: [cosmosInput], 23 | handler: storageQueueTrigger1, 24 | }); 25 | -------------------------------------------------------------------------------- /ts/src/functions/cosmosOutput1.ts: -------------------------------------------------------------------------------- 1 | import { app, InvocationContext, output } from '@azure/functions'; 2 | 3 | interface MyQueueItem { 4 | name: string; 5 | employeeId: string; 6 | address: string; 7 | } 8 | 9 | interface MyCosmosItem { 10 | id: string; 11 | name: string; 12 | employeeId: string; 13 | address: string; 14 | } 15 | 16 | export async function storageQueueTrigger1(queueItem: MyQueueItem, context: InvocationContext): Promise { 17 | return { 18 | id: `${queueItem.name}-${queueItem.employeeId}`, 19 | name: queueItem.name, 20 | employeeId: queueItem.employeeId, 21 | address: queueItem.address, 22 | }; 23 | } 24 | 25 | app.storageQueue('storageQueueTrigger1', { 26 | queueName: 'inputqueue', 27 | connection: 'MyStorageConnectionAppSetting', 28 | return: output.cosmosDB({ 29 | databaseName: 'MyDatabase', 30 | collectionName: 'MyCollection', 31 | createIfNotExists: true, 32 | connectionStringSetting: 'MyAccount_COSMOSDB', 33 | }), 34 | handler: storageQueueTrigger1, 35 | }); 36 | -------------------------------------------------------------------------------- /ts/src/functions/cosmosOutput2.ts: -------------------------------------------------------------------------------- 1 | import { app, InvocationContext, output } from '@azure/functions'; 2 | 3 | interface MyQueueItem { 4 | name: string; 5 | employeeId: string; 6 | address: string; 7 | } 8 | 9 | interface MyCosmosItem { 10 | id: string; 11 | name: string; 12 | employeeId: string; 13 | address: string; 14 | } 15 | 16 | export async function storageQueueTrigger1( 17 | queueItem: MyQueueItem, 18 | context: InvocationContext 19 | ): Promise { 20 | // 21 | return [ 22 | { 23 | id: 'John Henry-123456', 24 | name: 'John Henry', 25 | employeeId: '123456', 26 | address: 'A town nearby', 27 | }, 28 | { 29 | id: 'John Doe-123457', 30 | name: 'John Doe', 31 | employeeId: '123457', 32 | address: 'A town far away', 33 | }, 34 | ]; 35 | // 36 | } 37 | 38 | app.storageQueue('storageQueueTrigger1', { 39 | queueName: 'inputqueue', 40 | connection: 'MyStorageConnectionAppSetting', 41 | return: output.cosmosDB({ 42 | databaseName: 'MyDatabase', 43 | collectionName: 'MyCollection', 44 | createIfNotExists: true, 45 | connectionStringSetting: 'MyAccount_COSMOSDB', 46 | }), 47 | handler: storageQueueTrigger1, 48 | }); 49 | -------------------------------------------------------------------------------- /ts/src/functions/eventGridOutput1.ts: -------------------------------------------------------------------------------- 1 | import { app, EventGridPartialEvent, InvocationContext, output, Timer } from '@azure/functions'; 2 | 3 | export async function timerTrigger1(myTimer: Timer, context: InvocationContext): Promise { 4 | const timeStamp = new Date().toISOString(); 5 | return { 6 | id: 'message-id', 7 | subject: 'subject-name', 8 | dataVersion: '1.0', 9 | eventType: 'event-type', 10 | data: { 11 | name: 'John Henry', 12 | }, 13 | eventTime: timeStamp, 14 | }; 15 | } 16 | 17 | app.timer('timerTrigger1', { 18 | schedule: '0 */5 * * * *', 19 | return: output.eventGrid({ 20 | topicEndpointUri: 'MyEventGridTopicUriSetting', 21 | topicKeySetting: 'MyEventGridTopicKeySetting', 22 | }), 23 | handler: timerTrigger1, 24 | }); 25 | -------------------------------------------------------------------------------- /ts/src/functions/eventGridOutput2.ts: -------------------------------------------------------------------------------- 1 | import { app, EventGridPartialEvent, InvocationContext, output, Timer } from '@azure/functions'; 2 | 3 | export async function timerTrigger1(myTimer: Timer, context: InvocationContext): Promise { 4 | // 5 | const timeStamp = new Date().toISOString(); 6 | return [ 7 | { 8 | id: 'message-id', 9 | subject: 'subject-name', 10 | dataVersion: '1.0', 11 | eventType: 'event-type', 12 | data: { 13 | name: 'John Henry', 14 | }, 15 | eventTime: timeStamp, 16 | }, 17 | { 18 | id: 'message-id-2', 19 | subject: 'subject-name', 20 | dataVersion: '1.0', 21 | eventType: 'event-type', 22 | data: { 23 | name: 'John Doe', 24 | }, 25 | eventTime: timeStamp, 26 | }, 27 | ]; 28 | // 29 | } 30 | 31 | app.timer('timerTrigger1', { 32 | schedule: '0 */5 * * * *', 33 | return: output.eventGrid({ 34 | topicEndpointUri: 'MyEventGridTopicUriSetting', 35 | topicKeySetting: 'MyEventGridTopicKeySetting', 36 | }), 37 | handler: timerTrigger1, 38 | }); 39 | -------------------------------------------------------------------------------- /ts/src/functions/eventGridTrigger1.ts: -------------------------------------------------------------------------------- 1 | import { app, EventGridEvent, InvocationContext } from '@azure/functions'; 2 | 3 | export async function eventGridTrigger1(event: EventGridEvent, context: InvocationContext): Promise { 4 | context.log('Event grid function processed event:', event); 5 | } 6 | 7 | app.eventGrid('eventGridTrigger1', { 8 | handler: eventGridTrigger1, 9 | }); 10 | -------------------------------------------------------------------------------- /ts/src/functions/eventHubOutput1.ts: -------------------------------------------------------------------------------- 1 | import { app, InvocationContext, output, Timer } from '@azure/functions'; 2 | 3 | export async function timerTrigger1(myTimer: Timer, context: InvocationContext): Promise { 4 | const timeStamp = new Date().toISOString(); 5 | return `Message created at: ${timeStamp}`; 6 | } 7 | 8 | app.timer('timerTrigger1', { 9 | schedule: '0 */5 * * * *', 10 | return: output.eventHub({ 11 | eventHubName: 'myeventhub', 12 | connection: 'MyEventHubSendAppSetting', 13 | }), 14 | handler: timerTrigger1, 15 | }); 16 | -------------------------------------------------------------------------------- /ts/src/functions/eventHubOutput2.ts: -------------------------------------------------------------------------------- 1 | import { app, InvocationContext, output, Timer } from '@azure/functions'; 2 | 3 | export async function timerTrigger1(myTimer: Timer, context: InvocationContext): Promise { 4 | // 5 | const timeStamp = new Date().toISOString(); 6 | const message = `Message created at: ${timeStamp}`; 7 | return [`1: ${message}`, `2: ${message}`]; 8 | // 9 | } 10 | 11 | app.timer('timerTrigger1', { 12 | schedule: '0 */5 * * * *', 13 | return: output.eventHub({ 14 | eventHubName: 'myeventhub', 15 | connection: 'MyEventHubSendAppSetting', 16 | }), 17 | handler: timerTrigger1, 18 | }); 19 | -------------------------------------------------------------------------------- /ts/src/functions/eventHubTrigger1.ts: -------------------------------------------------------------------------------- 1 | import { app, InvocationContext } from '@azure/functions'; 2 | 3 | export async function eventHubTrigger1(message: unknown, context: InvocationContext): Promise { 4 | context.log('Event hub function processed message:', message); 5 | context.log('EnqueuedTimeUtc =', context.triggerMetadata.enqueuedTimeUtc); 6 | context.log('SequenceNumber =', context.triggerMetadata.sequenceNumber); 7 | context.log('Offset =', context.triggerMetadata.offset); 8 | } 9 | 10 | app.eventHub('eventHubTrigger1', { 11 | connection: 'myEventHubReadConnectionAppSetting', 12 | eventHubName: 'MyEventHub', 13 | cardinality: 'one', 14 | handler: eventHubTrigger1, 15 | }); 16 | -------------------------------------------------------------------------------- /ts/src/functions/eventHubTrigger2.ts: -------------------------------------------------------------------------------- 1 | import { app, InvocationContext } from '@azure/functions'; 2 | 3 | export async function eventHubTrigger1(messages: unknown[], context: InvocationContext): Promise { 4 | context.log(`Event hub function processed ${messages.length} messages`); 5 | for (let i = 0; i < messages.length; i++) { 6 | context.log('Event hub message:', messages[i]); 7 | context.log(`EnqueuedTimeUtc = ${context.triggerMetadata.enqueuedTimeUtcArray[i]}`); 8 | context.log(`SequenceNumber = ${context.triggerMetadata.sequenceNumberArray[i]}`); 9 | context.log(`Offset = ${context.triggerMetadata.offsetArray[i]}`); 10 | } 11 | } 12 | 13 | app.eventHub('eventHubTrigger1', { 14 | connection: 'myEventHubReadConnectionAppSetting', 15 | eventHubName: 'MyEventHub', 16 | cardinality: 'many', 17 | handler: eventHubTrigger1, 18 | }); 19 | -------------------------------------------------------------------------------- /ts/src/functions/httpTrigger1.ts: -------------------------------------------------------------------------------- 1 | import { app, HttpRequest, HttpResponseInit, InvocationContext } from '@azure/functions'; 2 | 3 | export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise { 4 | context.log(`Http function processed request for url "${request.url}"`); 5 | 6 | const name = request.query.get('name') || (await request.text()) || 'world'; 7 | 8 | return { body: `Hello, ${name}!` }; 9 | } 10 | 11 | app.http('httpTrigger1', { 12 | methods: ['GET', 'POST'], 13 | authLevel: 'anonymous', 14 | handler: httpTrigger1, 15 | }); 16 | -------------------------------------------------------------------------------- /ts/src/functions/httpTrigger2.ts: -------------------------------------------------------------------------------- 1 | import { app, HttpRequest, HttpResponseInit, InvocationContext } from '@azure/functions'; 2 | 3 | export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise { 4 | const category = request.params.category; 5 | const id = request.params.id; 6 | 7 | return { body: `Category: ${category}, ID: ${id}` }; 8 | } 9 | 10 | app.http('httpTrigger1', { 11 | methods: ['GET'], 12 | authLevel: 'anonymous', 13 | route: 'products/{category:alpha}/{id:int?}', 14 | handler: httpTrigger1, 15 | }); 16 | -------------------------------------------------------------------------------- /ts/src/functions/httpTrigger3.ts: -------------------------------------------------------------------------------- 1 | import { app, HttpRequest, HttpResponseInit, input, InvocationContext } from '@azure/functions'; 2 | 3 | const tableInput = input.table({ 4 | connection: 'MyStorageConnectionAppSetting', 5 | partitionKey: 'products', 6 | tableName: 'products', 7 | rowKey: '{id}', 8 | }); 9 | 10 | export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise { 11 | return { jsonBody: context.extraInputs.get(tableInput) }; 12 | } 13 | 14 | app.http('httpTrigger1', { 15 | methods: ['GET'], 16 | authLevel: 'anonymous', 17 | route: 'products/{id}', 18 | extraInputs: [tableInput], 19 | handler: httpTrigger1, 20 | }); 21 | -------------------------------------------------------------------------------- /ts/src/functions/httpTriggerBadAsync.ts: -------------------------------------------------------------------------------- 1 | // DO NOT USE THIS CODE 2 | import { app, HttpRequest, HttpResponseInit, InvocationContext } from '@azure/functions'; 3 | import * as fs from 'fs'; 4 | 5 | export async function httpTriggerBadAsync(request: HttpRequest, context: InvocationContext): Promise { 6 | let fileData: Buffer; 7 | fs.readFile('./helloWorld.txt', (err, data) => { 8 | if (err) { 9 | context.error(err); 10 | // BUG #1: This will result in an uncaught exception that crashes the entire process 11 | throw err; 12 | } 13 | fileData = data; 14 | }); 15 | // BUG #2: fileData is not guaranteed to be set before the invocation ends 16 | return { body: fileData }; 17 | } 18 | 19 | app.http('httpTriggerBadAsync', { 20 | methods: ['GET', 'POST'], 21 | authLevel: 'anonymous', 22 | handler: httpTriggerBadAsync, 23 | }); 24 | -------------------------------------------------------------------------------- /ts/src/functions/httpTriggerGoodAsync.ts: -------------------------------------------------------------------------------- 1 | // Recommended pattern 2 | import { app, HttpRequest, HttpResponseInit, InvocationContext } from '@azure/functions'; 3 | import * as fs from 'fs/promises'; 4 | 5 | export async function httpTriggerGoodAsync( 6 | request: HttpRequest, 7 | context: InvocationContext 8 | ): Promise { 9 | try { 10 | const fileData = await fs.readFile('./helloWorld.txt'); 11 | return { body: fileData }; 12 | } catch (err) { 13 | context.error(err); 14 | // This rethrown exception will only fail the individual invocation, instead of crashing the whole process 15 | throw err; 16 | } 17 | } 18 | 19 | app.http('httpTriggerGoodAsync', { 20 | methods: ['GET', 'POST'], 21 | authLevel: 'anonymous', 22 | handler: httpTriggerGoodAsync, 23 | }); 24 | -------------------------------------------------------------------------------- /ts/src/functions/httpTriggerStreamRequest.ts: -------------------------------------------------------------------------------- 1 | import { app, HttpRequest, HttpResponseInit, InvocationContext } from '@azure/functions'; 2 | import { createWriteStream } from 'fs'; 3 | import { Writable } from 'stream'; 4 | 5 | export async function httpTriggerStreamRequest( 6 | request: HttpRequest, 7 | context: InvocationContext 8 | ): Promise { 9 | const writeStream = createWriteStream(''); 10 | await request.body.pipeTo(Writable.toWeb(writeStream)); 11 | 12 | return { body: 'Done!' }; 13 | } 14 | 15 | app.http('httpTriggerStreamRequest', { 16 | methods: ['POST'], 17 | authLevel: 'anonymous', 18 | handler: httpTriggerStreamRequest, 19 | }); 20 | -------------------------------------------------------------------------------- /ts/src/functions/httpTriggerStreamResponse.ts: -------------------------------------------------------------------------------- 1 | import { app, HttpRequest, HttpResponseInit, InvocationContext } from '@azure/functions'; 2 | import { createReadStream } from 'fs'; 3 | 4 | export async function httpTriggerStreamResponse( 5 | request: HttpRequest, 6 | context: InvocationContext 7 | ): Promise { 8 | const body = createReadStream(''); 9 | 10 | return { body }; 11 | } 12 | 13 | app.http('httpTriggerStreamResponse', { 14 | methods: ['GET'], 15 | authLevel: 'anonymous', 16 | handler: httpTriggerStreamResponse, 17 | }); 18 | -------------------------------------------------------------------------------- /ts/src/functions/serviceBusOutput1.ts: -------------------------------------------------------------------------------- 1 | import { app, InvocationContext, output, Timer } from '@azure/functions'; 2 | 3 | export async function timerTrigger1(myTimer: Timer, context: InvocationContext): Promise { 4 | const timeStamp = new Date().toISOString(); 5 | return `Message created at: ${timeStamp}`; 6 | } 7 | 8 | app.timer('timerTrigger1', { 9 | schedule: '0 */5 * * * *', 10 | return: output.serviceBusQueue({ 11 | queueName: 'testqueue', 12 | connection: 'MyServiceBusConnection', 13 | }), 14 | handler: timerTrigger1, 15 | }); 16 | -------------------------------------------------------------------------------- /ts/src/functions/serviceBusOutput2.ts: -------------------------------------------------------------------------------- 1 | import { app, InvocationContext, output, Timer } from '@azure/functions'; 2 | 3 | export async function timerTrigger1(myTimer: Timer, context: InvocationContext): Promise { 4 | // 5 | const timeStamp = new Date().toISOString(); 6 | const message = `Message created at: ${timeStamp}`; 7 | return [`1: ${message}`, `2: ${message}`]; 8 | // 9 | } 10 | 11 | app.timer('timerTrigger1', { 12 | schedule: '0 */5 * * * *', 13 | return: output.serviceBusQueue({ 14 | queueName: 'testqueue', 15 | connection: 'MyServiceBusConnection', 16 | }), 17 | handler: timerTrigger1, 18 | }); 19 | -------------------------------------------------------------------------------- /ts/src/functions/serviceBusTrigger1.ts: -------------------------------------------------------------------------------- 1 | import { app, InvocationContext } from '@azure/functions'; 2 | 3 | export async function serviceBusQueueTrigger1(message: unknown, context: InvocationContext): Promise { 4 | context.log('Service bus queue function processed message:', message); 5 | context.log('EnqueuedTimeUtc =', context.triggerMetadata.enqueuedTimeUtc); 6 | context.log('DeliveryCount =', context.triggerMetadata.deliveryCount); 7 | context.log('MessageId =', context.triggerMetadata.messageId); 8 | } 9 | 10 | app.serviceBusQueue('serviceBusQueueTrigger1', { 11 | connection: 'MyServiceBusConnection', 12 | queueName: 'testqueue', 13 | handler: serviceBusQueueTrigger1, 14 | }); 15 | -------------------------------------------------------------------------------- /ts/src/functions/sqlInput1.ts: -------------------------------------------------------------------------------- 1 | import { app, HttpRequest, HttpResponseInit, input, InvocationContext } from '@azure/functions'; 2 | 3 | const sqlInput = input.sql({ 4 | commandText: 'select [Id], [order], [title], [url], [completed] from dbo.ToDo', 5 | commandType: 'Text', 6 | connectionStringSetting: 'SqlConnectionString', 7 | }); 8 | 9 | export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise { 10 | context.log('HTTP trigger and SQL input binding function processed a request.'); 11 | const toDoItems = context.extraInputs.get(sqlInput); 12 | return { 13 | jsonBody: toDoItems, 14 | }; 15 | } 16 | 17 | app.http('httpTrigger1', { 18 | methods: ['GET'], 19 | authLevel: 'anonymous', 20 | extraInputs: [sqlInput], 21 | handler: httpTrigger1, 22 | }); 23 | -------------------------------------------------------------------------------- /ts/src/functions/sqlInput2.ts: -------------------------------------------------------------------------------- 1 | import { app, HttpRequest, HttpResponseInit, input, InvocationContext } from '@azure/functions'; 2 | 3 | const sqlInput = input.sql({ 4 | commandText: 'select [Id], [order], [title], [url], [completed] from dbo.ToDo where Id = @Id', 5 | commandType: 'Text', 6 | parameters: '@Id={Query.id}', 7 | connectionStringSetting: 'SqlConnectionString', 8 | }); 9 | 10 | export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise { 11 | context.log('HTTP trigger and SQL input binding function processed a request.'); 12 | const toDoItem = context.extraInputs.get(sqlInput); 13 | return { 14 | jsonBody: toDoItem, 15 | }; 16 | } 17 | 18 | app.http('httpTrigger1', { 19 | methods: ['GET'], 20 | authLevel: 'anonymous', 21 | extraInputs: [sqlInput], 22 | handler: httpTrigger1, 23 | }); 24 | -------------------------------------------------------------------------------- /ts/src/functions/sqlInput3.ts: -------------------------------------------------------------------------------- 1 | import { app, HttpRequest, HttpResponseInit, input, InvocationContext } from '@azure/functions'; 2 | 3 | const sqlInput = input.sql({ 4 | commandText: 'DeleteToDo', 5 | commandType: 'StoredProcedure', 6 | parameters: '@Id={Query.id}', 7 | connectionStringSetting: 'SqlConnectionString', 8 | }); 9 | 10 | export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise { 11 | context.log('HTTP trigger and SQL input binding function processed a request.'); 12 | const toDoItems = context.extraInputs.get(sqlInput); 13 | return { 14 | jsonBody: toDoItems, 15 | }; 16 | } 17 | 18 | app.http('httpTrigger1', { 19 | methods: ['GET'], 20 | authLevel: 'anonymous', 21 | extraInputs: [sqlInput], 22 | handler: httpTrigger1, 23 | }); 24 | -------------------------------------------------------------------------------- /ts/src/functions/sqlOutput1.ts: -------------------------------------------------------------------------------- 1 | import { app, HttpRequest, HttpResponseInit, InvocationContext, output } from '@azure/functions'; 2 | 3 | const sqlOutput = output.sql({ 4 | commandText: 'dbo.ToDo', 5 | connectionStringSetting: 'SqlConnectionString', 6 | }); 7 | 8 | export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise { 9 | context.log('HTTP trigger and SQL output binding function processed a request.'); 10 | 11 | const body = await request.json(); 12 | context.extraOutputs.set(sqlOutput, body); 13 | return { status: 201 }; 14 | } 15 | 16 | app.http('httpTrigger1', { 17 | methods: ['POST'], 18 | authLevel: 'anonymous', 19 | extraOutputs: [sqlOutput], 20 | handler: httpTrigger1, 21 | }); 22 | -------------------------------------------------------------------------------- /ts/src/functions/sqlOutput2.ts: -------------------------------------------------------------------------------- 1 | import { app, HttpRequest, HttpResponseInit, InvocationContext, output } from '@azure/functions'; 2 | 3 | const sqlTodoOutput = output.sql({ 4 | commandText: 'dbo.ToDo', 5 | connectionStringSetting: 'SqlConnectionString', 6 | }); 7 | 8 | const sqlRequestLogOutput = output.sql({ 9 | commandText: 'dbo.RequestLog', 10 | connectionStringSetting: 'SqlConnectionString', 11 | }); 12 | 13 | export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise { 14 | context.log('HTTP trigger and SQL output binding function processed a request.'); 15 | 16 | const newLog = { 17 | RequestTimeStamp: Date.now(), 18 | ItemCount: 1, 19 | }; 20 | context.extraOutputs.set(sqlRequestLogOutput, newLog); 21 | 22 | const body = await request.json(); 23 | context.extraOutputs.set(sqlTodoOutput, body); 24 | 25 | return { status: 201 }; 26 | } 27 | 28 | app.http('httpTrigger1', { 29 | methods: ['POST'], 30 | authLevel: 'anonymous', 31 | extraOutputs: [sqlTodoOutput, sqlRequestLogOutput], 32 | handler: httpTrigger1, 33 | }); 34 | -------------------------------------------------------------------------------- /ts/src/functions/storageBlobInputAndOutput1.ts: -------------------------------------------------------------------------------- 1 | import { app, input, InvocationContext, output } from '@azure/functions'; 2 | 3 | const blobInput = input.storageBlob({ 4 | path: 'samples-workitems/{queueTrigger}', 5 | connection: 'MyStorageConnectionAppSetting', 6 | }); 7 | 8 | const blobOutput = output.storageBlob({ 9 | path: 'samples-workitems/{queueTrigger}-Copy', 10 | connection: 'MyStorageConnectionAppSetting', 11 | }); 12 | 13 | export async function storageQueueTrigger1(queueItem: unknown, context: InvocationContext): Promise { 14 | return context.extraInputs.get(blobInput); 15 | } 16 | 17 | app.storageQueue('storageQueueTrigger1', { 18 | queueName: 'myqueue-items', 19 | connection: 'MyStorageConnectionAppSetting', 20 | extraInputs: [blobInput], 21 | return: blobOutput, 22 | handler: storageQueueTrigger1, 23 | }); 24 | -------------------------------------------------------------------------------- /ts/src/functions/storageBlobTrigger1.ts: -------------------------------------------------------------------------------- 1 | import { app, InvocationContext } from '@azure/functions'; 2 | 3 | export async function storageBlobTrigger1(blob: Buffer, context: InvocationContext): Promise { 4 | context.log( 5 | `Storage blob function processed blob "${context.triggerMetadata.name}" with size ${blob.length} bytes` 6 | ); 7 | } 8 | 9 | app.storageBlob('storageBlobTrigger1', { 10 | path: 'samples-workitems/{name}', 11 | connection: 'MyStorageAccountAppSetting', 12 | handler: storageBlobTrigger1, 13 | }); 14 | -------------------------------------------------------------------------------- /ts/src/functions/storageBlobTriggerEventGrid1.ts: -------------------------------------------------------------------------------- 1 | import { app, InvocationContext } from '@azure/functions'; 2 | 3 | export async function storageBlobTrigger1(blob: Buffer, context: InvocationContext): Promise { 4 | context.log( 5 | `Storage blob function processed blob "${context.triggerMetadata.name}" with size ${blob.length} bytes` 6 | ); 7 | } 8 | 9 | app.storageBlob('storageBlobTrigger1', { 10 | path: 'samples-workitems/{name}', 11 | connection: 'MyStorageAccountAppSetting', 12 | source: 'EventGrid', 13 | handler: storageBlobTrigger1, 14 | }); 15 | -------------------------------------------------------------------------------- /ts/src/functions/storageQueueOutput1.ts: -------------------------------------------------------------------------------- 1 | import { app, HttpRequest, HttpResponseInit, InvocationContext, output } from '@azure/functions'; 2 | 3 | const queueOutput = output.storageQueue({ 4 | queueName: 'outqueue', 5 | connection: 'MyStorageConnectionAppSetting', 6 | }); 7 | 8 | export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise { 9 | const body = await request.text(); 10 | context.extraOutputs.set(queueOutput, body); 11 | return { body: 'Created queue item.' }; 12 | } 13 | 14 | app.http('httpTrigger1', { 15 | methods: ['GET', 'POST'], 16 | authLevel: 'anonymous', 17 | extraOutputs: [queueOutput], 18 | handler: httpTrigger1, 19 | }); 20 | -------------------------------------------------------------------------------- /ts/src/functions/storageQueueOutput2.ts: -------------------------------------------------------------------------------- 1 | import { app, HttpRequest, HttpResponseInit, InvocationContext, output } from '@azure/functions'; 2 | 3 | const queueOutput = output.storageQueue({ 4 | queueName: 'outqueue', 5 | connection: 'MyStorageConnectionAppSetting', 6 | }); 7 | 8 | export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise { 9 | // 10 | context.extraOutputs.set(queueOutput, ['message 1', 'message 2']); 11 | // 12 | return { body: 'Created queue item.' }; 13 | } 14 | 15 | app.http('httpTrigger1', { 16 | methods: ['GET', 'POST'], 17 | authLevel: 'anonymous', 18 | extraOutputs: [queueOutput], 19 | handler: httpTrigger1, 20 | }); 21 | -------------------------------------------------------------------------------- /ts/src/functions/storageQueueTrigger1.ts: -------------------------------------------------------------------------------- 1 | import { app, InvocationContext } from '@azure/functions'; 2 | 3 | export async function storageQueueTrigger1(queueItem: unknown, context: InvocationContext): Promise { 4 | context.log('Storage queue function processed work item:', queueItem); 5 | context.log('expirationTime =', context.triggerMetadata.expirationTime); 6 | context.log('insertionTime =', context.triggerMetadata.insertionTime); 7 | context.log('nextVisibleTime =', context.triggerMetadata.nextVisibleTime); 8 | context.log('id =', context.triggerMetadata.id); 9 | context.log('popReceipt =', context.triggerMetadata.popReceipt); 10 | context.log('dequeueCount =', context.triggerMetadata.dequeueCount); 11 | } 12 | 13 | app.storageQueue('storageQueueTrigger1', { 14 | queueName: 'myqueue-items', 15 | connection: 'MyStorageConnectionAppSetting', 16 | handler: storageQueueTrigger1, 17 | }); 18 | -------------------------------------------------------------------------------- /ts/src/functions/tableInput1.ts: -------------------------------------------------------------------------------- 1 | import { app, input, InvocationContext } from '@azure/functions'; 2 | 3 | const tableInput = input.table({ 4 | tableName: 'Person', 5 | partitionKey: 'Test', 6 | rowKey: '{queueTrigger}', 7 | connection: 'MyStorageConnectionAppSetting', 8 | }); 9 | 10 | interface PersonEntity { 11 | PartitionKey: string; 12 | RowKey: string; 13 | Name: string; 14 | } 15 | 16 | export async function storageQueueTrigger1(queueItem: unknown, context: InvocationContext): Promise { 17 | context.log('Node.js queue trigger function processed work item', queueItem); 18 | const person = context.extraInputs.get(tableInput); 19 | context.log('Person entity name: ' + person.Name); 20 | } 21 | 22 | app.storageQueue('storageQueueTrigger1', { 23 | queueName: 'myqueue-items', 24 | connection: 'MyStorageConnectionAppSetting', 25 | extraInputs: [tableInput], 26 | handler: storageQueueTrigger1, 27 | }); 28 | -------------------------------------------------------------------------------- /ts/src/functions/tableOutput1.ts: -------------------------------------------------------------------------------- 1 | import { app, HttpRequest, HttpResponseInit, InvocationContext, output } from '@azure/functions'; 2 | 3 | const tableOutput = output.table({ 4 | tableName: 'Person', 5 | connection: 'MyStorageConnectionAppSetting', 6 | }); 7 | 8 | interface PersonEntity { 9 | PartitionKey: string; 10 | RowKey: string; 11 | Name: string; 12 | } 13 | 14 | export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise { 15 | const rows: PersonEntity[] = []; 16 | for (let i = 1; i < 10; i++) { 17 | rows.push({ 18 | PartitionKey: 'Test', 19 | RowKey: i.toString(), 20 | Name: `Name ${i}`, 21 | }); 22 | } 23 | context.extraOutputs.set(tableOutput, rows); 24 | return { status: 201 }; 25 | } 26 | 27 | app.http('httpTrigger1', { 28 | methods: ['POST'], 29 | authLevel: 'anonymous', 30 | extraOutputs: [tableOutput], 31 | handler: httpTrigger1, 32 | }); 33 | -------------------------------------------------------------------------------- /ts/src/functions/timerTrigger1.ts: -------------------------------------------------------------------------------- 1 | import { app, InvocationContext, Timer } from '@azure/functions'; 2 | 3 | export async function timerTrigger1(myTimer: Timer, context: InvocationContext): Promise { 4 | context.log('Timer function processed request.'); 5 | } 6 | 7 | app.timer('timerTrigger1', { 8 | schedule: '0 */5 * * * *', 9 | handler: timerTrigger1, 10 | }); 11 | -------------------------------------------------------------------------------- /ts/src/functions/timerTriggerWithRetry.ts: -------------------------------------------------------------------------------- 1 | import { app, InvocationContext, Timer } from '@azure/functions'; 2 | 3 | export async function timerTriggerWithRetry(myTimer: Timer, context: InvocationContext): Promise { 4 | if (context.retryContext?.retryCount < 2) { 5 | throw new Error('Retry!'); 6 | } else { 7 | context.log('Timer function processed request.'); 8 | } 9 | } 10 | 11 | app.timer('timerTriggerWithRetry', { 12 | schedule: '0 */5 * * * *', 13 | retry: { 14 | strategy: 'fixedDelay', 15 | delayInterval: { 16 | seconds: 10, 17 | }, 18 | maxRetryCount: 4, 19 | }, 20 | handler: timerTriggerWithRetry, 21 | }); 22 | -------------------------------------------------------------------------------- /ts/src/functions/warmupTrigger1.ts: -------------------------------------------------------------------------------- 1 | import { app, InvocationContext, WarmupContext } from '@azure/functions'; 2 | 3 | export async function warmupFunction(warmupContext: WarmupContext, context: InvocationContext): Promise { 4 | context.log('Function App instance is warm.'); 5 | } 6 | 7 | app.warmup('warmup', { 8 | handler: warmupFunction, 9 | }); 10 | -------------------------------------------------------------------------------- /ts/src/invocationHooks1.ts: -------------------------------------------------------------------------------- 1 | import { app, PostInvocationContext, PreInvocationContext } from '@azure/functions'; 2 | 3 | app.hook.preInvocation((context: PreInvocationContext) => { 4 | if (context.invocationContext.options.trigger.type === 'httpTrigger') { 5 | context.invocationContext.log( 6 | `preInvocation hook executed for http function ${context.invocationContext.functionName}` 7 | ); 8 | } 9 | }); 10 | 11 | app.hook.postInvocation((context: PostInvocationContext) => { 12 | if (context.invocationContext.options.trigger.type === 'httpTrigger') { 13 | context.invocationContext.log( 14 | `postInvocation hook executed for http function ${context.invocationContext.functionName}` 15 | ); 16 | } 17 | }); 18 | -------------------------------------------------------------------------------- /ts/src/otelAppInsights.ts: -------------------------------------------------------------------------------- 1 | import { AzureFunctionsInstrumentation } from '@azure/functions-opentelemetry-instrumentation'; 2 | import { AzureMonitorLogExporter, AzureMonitorTraceExporter } from '@azure/monitor-opentelemetry-exporter'; 3 | import { getNodeAutoInstrumentations, getResourceDetectors } from '@opentelemetry/auto-instrumentations-node'; 4 | import { registerInstrumentations } from '@opentelemetry/instrumentation'; 5 | import { detectResourcesSync } from '@opentelemetry/resources'; 6 | import { LoggerProvider, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs'; 7 | import { NodeTracerProvider, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node'; 8 | 9 | const resource = detectResourcesSync({ detectors: getResourceDetectors() }); 10 | 11 | const tracerProvider = new NodeTracerProvider({ resource }); 12 | tracerProvider.addSpanProcessor(new SimpleSpanProcessor(new AzureMonitorTraceExporter())); 13 | tracerProvider.register(); 14 | 15 | const loggerProvider = new LoggerProvider({ resource }); 16 | loggerProvider.addLogRecordProcessor(new SimpleLogRecordProcessor(new AzureMonitorLogExporter())); 17 | 18 | registerInstrumentations({ 19 | tracerProvider, 20 | loggerProvider, 21 | instrumentations: [getNodeAutoInstrumentations(), new AzureFunctionsInstrumentation()], 22 | }); 23 | -------------------------------------------------------------------------------- /ts/src/otelOtlp.ts: -------------------------------------------------------------------------------- 1 | import { AzureFunctionsInstrumentation } from '@azure/functions-opentelemetry-instrumentation'; 2 | import { getNodeAutoInstrumentations, getResourceDetectors } from '@opentelemetry/auto-instrumentations-node'; 3 | import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http'; 4 | import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; 5 | import { registerInstrumentations } from '@opentelemetry/instrumentation'; 6 | import { detectResourcesSync } from '@opentelemetry/resources'; 7 | import { LoggerProvider, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs'; 8 | import { NodeTracerProvider, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node'; 9 | 10 | const resource = detectResourcesSync({ detectors: getResourceDetectors() }); 11 | 12 | const tracerProvider = new NodeTracerProvider({ resource }); 13 | tracerProvider.addSpanProcessor(new SimpleSpanProcessor(new OTLPTraceExporter())); 14 | tracerProvider.register(); 15 | 16 | const loggerProvider = new LoggerProvider({ resource }); 17 | loggerProvider.addLogRecordProcessor(new SimpleLogRecordProcessor(new OTLPLogExporter())); 18 | 19 | registerInstrumentations({ 20 | tracerProvider, 21 | loggerProvider, 22 | instrumentations: [getNodeAutoInstrumentations(), new AzureFunctionsInstrumentation()], 23 | }); 24 | -------------------------------------------------------------------------------- /ts/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es6", 5 | "outDir": "dist", 6 | "rootDir": ".", 7 | "sourceMap": true, 8 | "strict": false 9 | } 10 | } 11 | --------------------------------------------------------------------------------