前提
- dynamodbのテーブルは、パーティションキー/ソートキーを設定している、いわゆる複合プライマリキーを採用したテーブルを利用
- 同リクエストがあった場合、上書きしたくない。パーティションキー/ソートキーの組み合わせがすでに存在する場合はputしない
dynamodbのテーブル構成
パーティションキー: partition (string型)
ソートキー: sort (string型)
コード
命名は自信ない
import { DocumentClient } from "aws-sdk/clients/dynamodb";
export class DynamoRepository {
private client: DocumentClient;
constructor() {
this.client = new DocumentClient({
apiVersion: "2012-08-10",
region: "us-west-2"
});
}
async put(tableName: string, item: DocumentClient.PutItemInputAttributeMap) {
const params: DocumentClient.PutItemInput = {
TableName: tableName,
Item: item,
ExpressionAttributeNames: {
"#p": "partition",
"#s": "sort"
},
ConditionExpression: "attribute_not_exists(#p) AND attribute_not_exists(#s)"
};
return await this.client.put(params).promise();
};
}
動的にregionをいい感じにしたければいい感じにしていただけると
itemは以下の感じ
partition/sortは必須でそれ以外はお好きに
const item = {
partition: "hoge",
sort: "fuga",
piyo: "piyo",
data: {
key1: "key1",
key2: {
key3: 3,
key4: "key4"
}
}
};
import { DynamoRepository } from "../repository/DynamoRepository";
const repo = new DynamoRepository();
await repo.put("hogehoge", item);
的な感じで