+++ title = "HitCounter の使用" weight = 400 +++ ## スタックに HitCounter を追加する HitCounter の準備ができたのでアプリに実装していきましょう。 `src/CdkWorkshop/CdkWorkshopStack.cs` を開き、次のハイライトされたコードを追加します。 {{}} using Amazon.CDK; using Amazon.CDK.AWS.APIGateway; using Amazon.CDK.AWS.Lambda; using Constructs; namespace CdkWorkshop { public class CdkWorkshopStack : Stack { public CdkWorkshopStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) { // Defines a new lambda resource var hello = new Function(this, "HelloHandler", new FunctionProps { Runtime = Runtime.NODEJS_14_X, // execution environment Code = Code.FromAsset("lambda"), // Code loaded from the "lambda" directory Handler = "hello.handler" // file is "hello", function is "handler" }); var helloWithCounter = new HitCounter(this, "HelloHitCounter", new HitCounterProps { Downstream = hello }); // defines an API Gateway REST API resource backed by our "hello" function. new LambdaRestApi(this, "Endpoint", new LambdaRestApiProps { Handler = helloWithCounter.Handler }); } } } {{}} API Gateway のハンドラーを `hello` から `helloWithCounter.handler` に変更しています。エンドポイントがアクセスされるたびに、API Gateway が HitCounter ハンドラーにリクエストをルーティングし、そのリクエストが記録され、`hello` Lambda 関数に引き渡します。レスポンスはユーザーに返されるまで逆順でリレーされます。 ## デプロイ ``` cdk deploy ``` デプロイには少し時間がかかります。 出力は次のとおりです。 ``` CdkWorkshopStack.Endpoint8024A810 = https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/ ``` ## テスト 準備ができたので実行してみましょう。(「deploy」コマンドの実行結果からAPIのURLを確認してください) `curl` コマンドまたはウェブブラウザを使って、エンドポイントの URL にアクセスしてみてください。 (`-i` オプションをつけて実行すると、HTTP レスポンスのフィールドとステータコードが表示されます。) ``` curl -i https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/ ``` 実行すると、何かがうまくいってないことに気づきます。 ```text HTTP/2 502 Bad Gateway ... {"message": "Internal server error"} ``` 原因を調べて、修正してみましょう。