2021年7月第2週レポート

インプット

📝 Azure Functions For TypeScript

最近はAzure Functionsを使ってバックエンドサービスの実装を試みています。言語は自分が一番と得意とするTypeScriptを使っています。MS公式ドキュメントではJavaScriptによるドキュメントは揃っていますが、TypeScriptについてはサポートはされているもののそれほど言及されていません。とはいえJavaScript環境と比べて変化があるのはfunction.jsonでのエントリポイントの指定くらいなので、それほど苦労することもないかと思います。

プロジェクトの作成

プロジェクトのセットアップにはAzure Function Core Toolsを使うのがいいと思います。

まずは、Azure Function Core Toolsを使ってプロジェクトを作ります。

func init

ランタイムはnodeを指定します。

Select a number for worker runtime:
1. dotnet
2. dotnet (isolated process)
3. node
4. python
5. powershell
6. custom
Choose option: 3

使用言語としてTypeScriptを指定できるのでそちらを指定します。

Select a number for language:
1. javascript
2. typescript
Choose option: 2

tsconfig.jsonやpackage.jsonといったTypeScriptプロジェクトに必要なファイルが生成されます。

Writing .funcignore
Writing package.json
Writing tsconfig.json
Writing .gitignore
Writing host.json
Writing local.settings.json
Writing /Users/d_yama/functions-project/second-app/.vscode/extensions.json

必要なパッケージをインストールするためyarnnpm installを実行しておきます。

関数を作る

Azure Function Core Toolsを使って関数を作ると、function.jsindex.tsにスケルトンコードが埋め込まれて生成されます。

func new

Durable Functionsを含め、任意のトリガーを選択できます。

Select a number for template:
1. Azure Blob Storage trigger
2. Azure Cosmos DB trigger
3. Durable Functions activity
4. Durable Functions entity
5. Durable Functions Entity HTTP starter
6. Durable Functions HTTP starter
7. Durable Functions orchestrator
8. Azure Event Grid trigger
9. Azure Event Hub trigger
10. HTTP trigger
11. IoT Hub (Event Hub)
12. Kafka output
13. Kafka trigger
14. Azure Queue Storage trigger
15. RabbitMQ trigger
16. SendGrid
17. Azure Service Bus Queue trigger
18. Azure Service Bus Topic trigger
19. SignalR negotiate HTTP trigger
20. Timer trigger
Choose option: 

プロジェクト構成

Azure Function Core ToolsでTypeScriptを指定してプロジェクトを作成したとき、TSコードをトランスパイルしたJSコードはdistディレクトリに出力されるようになっています。

なお、func newで関数を作成したときのfunction.jsonは次のようになっている。

{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ],
  "scriptFile": "../dist/getStocks/index.js"
}

scriptFileプロパティに指定されたパスの関数が実行されるようになっています(TSコードが直接実行されるわけではない)

関数コード

指定したエントリポイントファイル内のデフォルトエクスポートされている関数がFunctionsでは実行されます。

export default function (context: Context) {
 
}

ContextオブジェクトなどFunctionsから渡ってくるものは型定義が用意されています。しかし各種トリガーやバインディングで渡ってくるオブジェクトはanyとなるので、その辺りは自分で型アノテーションで注釈する必要があります。

アウトプット

目立ったものはなし。

Profile
d_yama
元Microsoft MVP for Windows Development(2018-2020)
Sub-category : Windows Mixed Reality
Search