4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

typescript + dynamodb documentClient で条件付きput

4
Last updated at Posted at 2019-09-19

前提

  • 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);

的な感じで

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?