LoginSignup
0
0

CDK×Lambda×golang×Dynamoでアプリを作ってみる DynamoDB処理のLambda実装編PUT&DELETE(第五回)

Posted at

さて、今回は更新と削除のメソッドを作成していきたいと思います!
とは言っても構造体などはgetItemやputItemに似ているので非常に分かりやすかったです。

とりあえず全体像は以下の通りになります。

package main

import (
	"encoding/json"
	"net/http"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/dynamodb"
	"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)

var (
	tableName = "MyDynamoDB"
	dynamoDb  = dynamodb.New(session.Must(session.NewSession()))
)

type Item struct {
	ID      string `json:"id"`
	Content string `json:"content"`
}

func getItem(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
	id := request.QueryStringParameters["id"]

	input := &dynamodb.GetItemInput{
		TableName: aws.String(tableName),
		Key: map[string]*dynamodb.AttributeValue{
			"id": {
				S: aws.String(id),
			},
		},
	}
	result, err := dynamoDb.GetItem(input)

	if err != nil {
		return events.APIGatewayProxyResponse{
			StatusCode: http.StatusInternalServerError,
			Body:       err.Error(),
		}, nil
	}

	item := Item{}
	err = dynamodbattribute.UnmarshalMap(result.Item, &item)
	if err != nil {
		return events.APIGatewayProxyResponse{
			StatusCode: http.StatusInternalServerError,
			Body:       err.Error(),
		}, nil
	}

	body, _ := json.Marshal(item)
	return events.APIGatewayProxyResponse{
		StatusCode: http.StatusOK,
		Body:       string(body),
	}, nil
}

func putItem(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
	item := Item{}
	err := json.Unmarshal([]byte(request.Body), &item)
	if err != nil {
		return events.APIGatewayProxyResponse{
			StatusCode: http.StatusBadRequest,
			Body:       err.Error(),
		}, nil
	}

	input := &dynamodb.PutItemInput{
		TableName: aws.String(tableName),
		Item: map[string]*dynamodb.AttributeValue{
			"id": {
				S: aws.String(item.ID),
			},
			"content": {
				S: aws.String(item.Content),
			},
		},
	}
	_, err = dynamoDb.PutItem(input)

	if err != nil {
		return events.APIGatewayProxyResponse{
			StatusCode: http.StatusInternalServerError,
			Body:       err.Error(),
		}, nil
	}

	return events.APIGatewayProxyResponse{
		StatusCode: http.StatusCreated,
	}, nil
}

func updateItem(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error){
	item := Item{}
	err := json.Unmarshal([]byte(request.Body), &item)
	if err != nil {
		return events.APIGatewayProxyResponse{
			StatusCode: http.StatusBadRequest,
			Body: err.Error(),
		}, nil
	}
	input := &dynamodb.UpdateItemInput{
		TableName: aws.String(tableName),
		Key: map[string]*dynamodb.AttributeValue{
			"id": {
				S: aws.String(item.ID),
			},
		},
		UpdateExpression: aws.String("set Content = :c"),
		ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
			":c": {
				S: aws.String(item.Content),
			},
		},
	}

	_, err = dynamoDb.UpdateItem(input)
	if err != nil {
		return events.APIGatewayProxyResponse{
			StatusCode: http.StatusBadRequest,
			Body: err.Error(),
		}, nil
	}

	return events.APIGatewayProxyResponse{
		StatusCode: http.StatusNoContent,
		Body: "アイテムが更新されました。",
	}, nil
}

func deleteItem(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error){
	item := Item{}
	err := json.Unmarshal([]byte(request.Body), &item)
	if err != nil {
		return events.APIGatewayProxyResponse{
			StatusCode: http.StatusBadRequest,
			Body: err.Error(),
		}, nil
	}

	input := dynamodb.DeleteItemInput{
		TableName: aws.String(tableName),
		Key: map[string] *dynamodb.AttributeValue{
			"id": {
				S: aws.String(item.ID),
			},
		},
	}
	_, err = dynamoDb.DeleteItem(&input)
	if err != nil {
		return events.APIGatewayProxyResponse{
			StatusCode: http.StatusBadRequest,
			Body: err.Error(),
		}, nil
	}

	return events.APIGatewayProxyResponse{
		StatusCode: http.StatusNoContent,
	}, nil

}

func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
	switch request.HTTPMethod {
	case "GET":
		return getItem(request)
	case "POST":
		return putItem(request)
	case "PUT":
		return updateItem(request)
	case "DELETE":
		return deleteItem(request)
	default:
		return events.APIGatewayProxyResponse{
			StatusCode: http.StatusMethodNotAllowed,
		}, nil
	}
}

func main() {
	lambda.Start(handler)
}

そして、今回追加した関数は以下の部分です。

func updateItem(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error){
	item := Item{}
	err := json.Unmarshal([]byte(request.Body), &item)
	if err != nil {
		return events.APIGatewayProxyResponse{
			StatusCode: http.StatusBadRequest,
			Body: err.Error(),
		}, nil
	}
    input := &dynamodb.UpdateItemInput{
    	TableName: aws.String(tableName),
    	Key: map[string]*dynamodb.AttributeValue{
    		"id": {
    			S: aws.String(item.ID),
    		},
    	},
    	UpdateExpression: aws.String("set Content = :c"),
    	ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
    		":c": {
    			S: aws.String(item.Content),
    		},
    	},
    }

	_, err = dynamoDb.UpdateItem(input)
	if err != nil {
		return events.APIGatewayProxyResponse{
			StatusCode: http.StatusBadRequest,
			Body: err.Error(),
		}, nil
	}

	return events.APIGatewayProxyResponse{
		StatusCode: http.StatusNoContent,
		Body: "アイテムが更新されました。",
	}, nil
}

func deleteItem(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error){
	item := Item{}
	err := json.Unmarshal([]byte(request.Body), &item)
	if err != nil {
		return events.APIGatewayProxyResponse{
			StatusCode: http.StatusBadRequest,
			Body: err.Error(),
		}, nil
	}

	input := dynamodb.DeleteItemInput{
		TableName: aws.String(tableName),
		Key: map[string] *dynamodb.AttributeValue{
			"id": {
				S: aws.String(item.ID),
			},
		},
	}
	_, err = dynamoDb.DeleteItem(&input)
	if err != nil {
		return events.APIGatewayProxyResponse{
			StatusCode: http.StatusBadRequest,
			Body: err.Error(),
		}, nil
	}

	return events.APIGatewayProxyResponse{
		StatusCode: http.StatusNoContent,
	}, nil

}

今回はここを詳しく見ていきたいと思います!とは言ってもあまり新しい考え方は出てこないので、追加で説明が必要な箇所に限定したいと思います。

おそらく以前までのコードを理解できている方はすんなり理解できるようなコードとなっています。

updateItem関数

今回新しく出てきた?部分としては以下の部分かなと思います。
ほとんど同じような書き方ですが、更新にはいくつかオプションというか、アクションを指定することができます。
そのアクションをUpdateExpressionで指定します。

input := &dynamodb.UpdateItemInput{
	TableName: aws.String(tableName),
	Key: map[string]*dynamodb.AttributeValue{
		"id": {
			S: aws.String(item.ID),
		},
	},
	UpdateExpression: aws.String("set Content = :c"),
	ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
		":c": {
			S: aws.String(item.Content),
		},
	},
}

UpdateExpressionの説明が以下の通りで、ちょっと長いですがapi.goに書かれています。

service/dynamodb/api.go
// An expression that defines one or more attributes to be updated, the action
	// to be performed on them, and new values for them.
	//
	// The following action values are available for UpdateExpression.
	//
	//    * SET - Adds one or more attributes and values to an item. If any of these
	//    attributes already exist, they are replaced by the new values. You can
	//    also use SET to add or subtract from an attribute that is of type Number.
	//    For example: SET myNum = myNum + :val SET supports the following functions:
	//    if_not_exists (path, operand) - if the item does not contain an attribute
	//    at the specified path, then if_not_exists evaluates to operand; otherwise,
	//    it evaluates to path. You can use this function to avoid overwriting an
	//    attribute that may already be present in the item. list_append (operand,
	//    operand) - evaluates to a list with a new element added to it. You can
	//    append the new element to the start or the end of the list by reversing
	//    the order of the operands. These function names are case-sensitive.
	//
	//    * REMOVE - Removes one or more attributes from an item.
	//
	//    * ADD - Adds the specified value to the item, if the attribute does not
	//    already exist. If the attribute does exist, then the behavior of ADD depends
	//    on the data type of the attribute: If the existing attribute is a number,
	//    and if Value is also a number, then Value is mathematically added to the
	//    existing attribute. If Value is a negative number, then it is subtracted
	//    from the existing attribute. If you use ADD to increment or decrement
	//    a number value for an item that doesn't exist before the update, DynamoDB
	//    uses 0 as the initial value. Similarly, if you use ADD for an existing
	//    item to increment or decrement an attribute value that doesn't exist before
	//    the update, DynamoDB uses 0 as the initial value. For example, suppose
	//    that the item you want to update doesn't have an attribute named itemcount,
	//    but you decide to ADD the number 3 to this attribute anyway. DynamoDB
	//    will create the itemcount attribute, set its initial value to 0, and finally
	//    add 3 to it. The result will be a new itemcount attribute in the item,
	//    with a value of 3. If the existing data type is a set and if Value is
	//    also a set, then Value is added to the existing set. For example, if the
	//    attribute value is the set [1,2], and the ADD action specified [3], then
	//    the final attribute value is [1,2,3]. An error occurs if an ADD action
	//    is specified for a set attribute and the attribute type specified does
	//    not match the existing set type. Both sets must have the same primitive
	//    data type. For example, if the existing data type is a set of strings,
	//    the Value must also be a set of strings. The ADD action only supports
	//    Number and set data types. In addition, ADD can only be used on top-level
	//    attributes, not nested attributes.
	//
	//    * DELETE - Deletes an element from a set. If a set of values is specified,
	//    then those values are subtracted from the old set. For example, if the
	//    attribute value was the set [a,b,c] and the DELETE action specifies [a,c],
	//    then the final attribute value is [b]. Specifying an empty set is an error.
	//    The DELETE action only supports set data types. In addition, DELETE can
	//    only be used on top-level attributes, not nested attributes.
	//
	// You can have many actions in a single expression, such as the following:
	// SET a=:value1, b=:value2 DELETE :value3, :value4, :value5
	//
	// For more information on update expressions, see Modifying Items and Attributes
	// (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.Modifying.html)
	// in the Amazon DynamoDB Developer Guide.

まとめると以下のような感じでしょうか。
名前がupdateなので更新だけかと思ってましたが、REMOVEとかDELETEもあるんですね〜。

アクション 説明
SET 1つ以上の属性とその値をアイテムに追加。存在しない属性の場合、新しくその属性が作成される。既に存在する場合は値を置き換える。数値属性に対して値を加算または減算できる。
関数:
- if_not_exists(path, operand):指定されたパスに属性が存在しない場合に operand を評価する。
- list_append(operand, operand):リストに新しい要素を追加する。
REMOVE 1つ以上の属性をアイテムから削除。
ADD 指定された値をアイテムに追加。属性が存在する場合は数値の加算またはセットへの追加を行う。数値とセットデータ型のみサポート。トップレベルの属性にのみ使用可能。
DELETE セットから要素を削除。指定した値を既存のセットから引く。セットデータ型のみサポート。トップレベルの属性にのみ使用可能。

UpdateExpressionは、どの属性にどのような操作を行うかを定義する式です。例えば、属性を追加、削除、または変更する操作を指定します。

そして、ExpressionAttributeValuesと続けて使用していますが、このマップは、UpdateExpression内で使用されるプレースホルダー(今回だと:cの部分)に対応する実際の値を提供します。

つまり、以下の部分では、指定されたitem.ID を持つDynamoDBのアイテムを見つけ、そのアイテムの Content 属性を :c として指定された値(この場合は item.Content)に更新します。

input := &dynamodb.UpdateItemInput{
	TableName: aws.String(tableName),
	Key: map[string]*dynamodb.AttributeValue{
		"id": {
			S: aws.String(item.ID),
		},
	},
	UpdateExpression: aws.String("set Content = :c"),
	ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
		":c": {
			S: aws.String(item.Content),
		},
	},
}	

set

ちなみに、以下のようにまとめてSETして更新することもできます。

UpdateExpression: aws.String("set Content = :c, OtherAttribute = :o"),
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
    ":c": {
        S: aws.String(item.Content),
    },
    ":o": {
        S: aws.String(item.OtherAttribute),
    },
}

他にも数値の加算減算もできるようです。
例えば以下の例だとすでにあるAge属性にプレースホルダー:vを加算するようsetしていて、具体的な値をExpressionAttributeValuesでvにN(Number)で1を渡しています。

つまり、既存のage属性に+1して更新するような書き方となります。
数値なのにaws.Stringっていうのが若干気持ち悪いなと思いますが、DynamoDBでは内部的に数値を文字列として扱うためらしいです。。。

UpdateExpression: aws.String("set Age = Age + :v"),
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
    ":v": {
        N: aws.String("1"),
    },
}

あとは、list_appendのような関数が用意されていてそれを使えば、例えばリストに新しい要素を加えることができます。

以下の場合は、Tagsというリストにプレースホルダー:tを追加しています。
具体的な値はExpressionAttributeValuesに書かれていて、:tに対してL(リスト型)で"NewTag"という文字列を追加しています。

UpdateExpression: aws.String("set Tags = list_append(Tags, :t)"),
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
    ":t": {
        L: []dynamodb.AttributeValue{
            {S: aws.String("NewTag")},
        },
    },
}

ついでに、残りのアクションも見ておきます。

REMOVE 属性を取り除く

まずremoveですが、これは単純でアイテムから1つ以上の属性を取り除きます。deleteと混同しそうですが、後述するようにdeleteの場合はセットから要素を削除するので、属性を取り除くわけでありません。

UpdateExpression: aws.String("remove desginatedAttribute")

setと同様に複数をまとめてremoveすることもできます

UpdateExpression: aws.String("remove Attribute1, Attribute2")

ADD 数値かセットデータのみ

続いて、addですが、数値セットデータ型の属性のみ使用できます。

  • 数値の場合
    属性が存在する場合、指定した値が既存の値に加算されますが、属性が存在しない場合は、0とみなし加算されます。

例えば、以下の場合、Score属性が存在しない場合は10となり、既にScore属性に仮に5が入っている場合、結果は15となります。

UpdateExpression: aws.String("ADD Score :inc"),
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
    ":inc": {
        N: aws.String("10"),
    },
}
  • セットデータの場合
    ["42.2", "-19", "7.5", "3.14"]のようなセットに対して追加することができます。

以下の場合、 次のような形のセットデータが既に存在している場合は、"SS": ["something", "something"]このセットデータにSS(String Set)でnewTagのように指定して追加することができます。

また、属性が存在しない場合は、セットは空のセットから始まります。

UpdateExpression: aws.String("ADD Tags :newTag"),
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
    ":newTag": {
        SS: []*string{aws.String("urgent"), aws.String("important")},
    },
}

余談ですが、リストとセットはどちらも配列(のように)値を保持することができますが、リストは同じ値を保持できる一方でセットは同じ値を保持できないです。

もちろん、以下のようにNS(Numbers Set)で追加することも可能です。

UpdateExpression: aws.String("add Numbers :n"),
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
    ":n": {
        NS: []*string{"3"},
    },
}

DELETE セットデータから要素を取り除く

最後にdeleteですが、前述しましたが、こちらは属性の削除ではなく、セットから要素を取り除きます。
つまり、addの逆だと考えると分かりやすいですね。ただ数値や文字列、バイナリなど他のデータ型には使用できないので注意です。

例えば、以下の場合は"TagToRemove"という文字列をTagsというセットデータ型の属性から削除しています。

UpdateExpression: aws.String("delete Tags :t"),
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
    ":t": {
        SS: []string{"TagToRemove"},
    },
}

つまり、例えばTags属性が["Tag1","Tag2", "TagsToRemove"]だとした場合、このdeleteを実行すると["Tag1","Tag2"]になるということですね。

おまけ

またdeleteに限ったことではないですが、他のアクションと組み合わせて使用することもできます。
例えば、以下のようにsetremoveを組み合わせて使ったりすることも可能です。

UpdateExpression: aws.String("set Content = :c remove ObsoleteAttribute"),
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
    ":c": {
        S: aws.String("Updated Content"),
    },
}

deleteItem関数

続いて、deleteItem関数ですが、こちらは特に真新しい考え方はなく、dynamoDb.DeleteItemでどのitemを削除するのがdynamodb.DeleteItemInputでテーブル名やPKを指定して指定したIDに該当するアイテムを削除しています。

updateItemのremoveやdeleteとは異なり、アイテムを削除します。

	input := dynamodb.DeleteItemInput{
		TableName: aws.String(tableName),
		Key: map[string]*dynamodb.AttributeValue{
			"id": {
				S: aws.String(item.ID),
			},
		},
	}
	_, err = dynamoDb.DeleteItem(&input)

まとめ

さて、全五回でとりあえずCRUD処理をlambdaで記述して実行できるようになりました。かなり基本的な書き方?しかしていないですが、初めて触ったのでかなり学びもありました。

ただ、ライブラリが充実しているためドキュメントにジャンプすれば英語ではありますが説明も書かれているのでコーディングで迷宮入りする可能性はかなり難しいことをしない限りはなさそうです。

むしろDynamoDBの理解や設計の方が重要になってくる気がします。

こういった感想を踏まえて、今後は以下の学習をまとめていく予定ですので気になった初学者の方は、見てもらえると少しくらいは参考になるかもしれません🙌

  • DynamoDBのパーティション設計
    ここでは掲示板か何か(未定)を作る想定で、GSIやLSIを使いつつ、かつGSIオーバーローディングパターンなどベストプラクティも踏まえながら設計しようと考えています。

  • IAMで権限の追加
    これはそこまでコードを追加しなくても良いですが、復習がてらIAMを過去にSAPを取得したときの学習記録を振り返りながらまとめていきます。

  • &dynamodb.QueryInputを使用
    これはかなり使って試してみたい。今回はgetItemでデータを取得していますが、パーティション設計する際に、どのようなユースケースが想定されるか考え、クエリも同時に考える必要があると思うので、どういう書き方ができるのかまとめていきます。

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