-
Notifications
You must be signed in to change notification settings - Fork 0
/
create.go
65 lines (57 loc) · 1.54 KB
/
create.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package dygo
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
)
const opCreate = "Create"
// Create creates a new item in DynamoDB.
// It validates the item using the user defined Validate() method.
//
// Example :
//
// newData := dataItem{
// PK: PK,
// SK: SK,
// EntityType: "room",
// PhysicalName: "physical_name_11",
// LogicalName: "logical_name_11",
// }
//
// err = db.
// Item(newData).
// Create(context.Background())
//
// Important : dataItem must implement Validate() method.
func (i *Item) Create(ctx context.Context) error {
if i.err != nil {
return i.err
}
av, err := attributevalue.MarshalMap(i.item)
if err != nil {
return dynamoError().method(opCreate).message(err.Error())
}
err = i.item.Validate()
if err != nil {
return dynamoError().method(opCreate).message(err.Error())
}
expr, err := i.createItemExpression()
if err != nil {
return dynamoError().method(opCreate).message(err.Error())
}
input := dynamodb.PutItemInput{
Item: av,
TableName: aws.String(i.c.tableName),
ExpressionAttributeNames: expr.Names(),
ExpressionAttributeValues: expr.Values(),
ConditionExpression: expr.Condition(),
}
if _, err := i.c.client.PutItem(context.TODO(), &input); err != nil {
if err := getDynamoDBError(opCreate, err); err != nil {
return err
}
return dynamoError().method(opCreate).message(err.Error())
}
return nil
}