はじめに
TypeScriptでDynamoDBの書き込みを実装する機会があったのでメモとして残しておきます。
今回はCloudFormationでの構築からやってみようと思います。
本題
DynamoDB構築
今回はCloudFormationを使用して構築します。
テーブル定義
KeyType | KeyType | AttributeType |
---|---|---|
HASH | SampleKey | 文字列 |
CloudFormation定義
cloudformation.yml
AWSTemplateFormatVersion: 2010-09-09 Description: Init DynamoDb. Parameters: Env: Type: String AllowedValues: - prod - stg - dev SystemName: Type: String Default: Sample Resources: SampleTable: Type: "AWS::DynamoDB::Table" Properties: TableName: SampleTable AttributeDefinitions: - AttributeName: SampleKey AttributeType: S KeySchema: - AttributeName: SampleKey KeyType: HASH ProvisionedThroughput: ReadCapacityUnits: 5 WriteCapacityUnits: 5 Tags: - Key: Name Value: !Join ["-", [!Ref Env, !Ref SystemName, SampleTable]] Outputs: SampleTableArn: Value: !GetAtt SampleTable.Arn
LambdaからDynamoDBに書き込む
先ほど作成したSampleTableにItemを追加するサンプルコードです。
import { DynamoDB } from "aws-sdk"; const ddbdc = new DynamoDB.DocumentClient(); export const handler = (event: any) => { const ddbdcParams = { TableName: "SampleTable", Item: { SampleKey: "key1", value: "Value1", }, }; ddbdc.put(ddbdcParams, function (err, data) { if (err) { console.log(err); } else { ddbdc.scan({ TableName: "SampleTable" }, function (err, data) { if (err) { console.log("Error", err.code); } else { console.log("Table Items are ", data); } }); } }); };
実装参考元
LambdaからDynamoDBの読み書きを行う - Qiita
実行
実行はSAM LocalでLambdaをローカル実行しています。
START RequestId: 44a24952-f12c-1dbb-0cba-584099addf56 Version: $LATEST 2020-05-23T04:41:37.375Z 44a24952-f12c-1dbb-0cba-584099addf56 INFO Table Items are { Items: [ { value: 'Value1', SampleKey: 'key1' } ], Count: 1, ScannedCount: 1 } END RequestId: 44a24952-f12c-1dbb-0cba-584099addf56
テーブルに項目が追加されていることがわかります。
おわりに
TypeScriptでDynamoDB読み書きをしてみました。
今後はLambdaでTypeScriptを使用する方法、SAMの環境構築もご紹介できたらいいなーと思っています:)