LoginSignup
0
0

More than 1 year has passed since last update.

Azure Functions でキューをトリガーに関数を動かして、結果を別のキューに積む(JavaScript)

Last updated at Posted at 2021-08-30

ベースの関数と設定

src/FunctionName/index.ts
import { AzureFunction, Context } from '@azure/functions';

export const functionName: AzureFunction = async (context: Context, inputMessage: any): Promise<void> => {
    context.log(`function name ran with ${inputMessage}`);

    const data = doSomething();
    context.bindings.outputMessage = {data: data};
};
src/FunctionName/function.json
{
  "bindings": [
    {
      "name": "inputMessage",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "input-queue-name",
      "connection": "AzureWebJobsStorage"
    },
    {
      "name": "outputMessage",
      "type": "queue",
      "direction": "out",
      "queueName": "output-queue-name",
      "connection": "AzureWebJobsStorage"
    }
  ],
  "scriptFile": "../dist/FunctionName/index.js"
}
  • トリガー側のキューの name は何でも良いはず。
  • トリガー側のキューの direction は in を指定する。
  • バインド側のキューの namecontext.bindings.<name> のようにバインドするときのプロパティ名になる
  • バインド側のキューの direction は out を指定する。
  • connectionAzureWebJobsStorage はおまじないだと思っている。 AzureWebJobsStorage は環境変数で定義されているべきもの。- connection を指定しない場合でも、AzureWebJobsStorage を探す仕様らしい。 ちなみに、ローカル環境では local.settings.json に環境変数を定義するようドキュメントに記載があるが、なぜか読み込めなかったため、 docker-compose.ymlenveronment に定義した。

テスト

テストするとき、関数の第1引数 Context は以下のようにモジュール化することができます。(jest を使っている前提です。)
参考

tests/modules/defaultContext.ts
import { Context } from '@azure/functions';

export const context =  ({ log: jest.fn() } as unknown) as Context;

Azure Queue Storage の CLI

キューを作ったり削除したりするコマンドは、 az storage queue ...
https://docs.microsoft.com/ja-jp/cli/azure/storage/queue?view=azure-cli-latest

キューに値を入れたり削除したりするのは、 az storage message ...
https://docs.microsoft.com/ja-jp/cli/azure/storage/message?view=azure-cli-latest#az_storage_message_delete

sample
// message は base64 にエンコードする必要がある

az storage message put --content $(echo -n "test"|base64) -q input-queue-name --connection-string=""
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0