Created
May 6, 2022 04:28
-
-
Save wattanakorn495/769caff303bb0555ca3fc98c1233741f to your computer and use it in GitHub Desktop.
dynamodb put example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "context" | |
| "encoding/json" | |
| "github.com/aws/aws-lambda-go/events" | |
| "github.com/aws/aws-sdk-go/aws/session" | |
| "github.com/aws/aws-sdk-go/service/dynamodb" | |
| "github.com/guregu/dynamo" | |
| "go.uber.org/zap" | |
| ) | |
| var svc *dynamodb.DynamoDB | |
| var logger *zap.Logger | |
| // type Product struct { | |
| // StoreID string | |
| // SKU string | |
| // Tag string | |
| // Price int | |
| // DiscountPrice int | |
| // } | |
| func createEvent() { | |
| var record events.DynamoDBEventRecord | |
| // event.Records | |
| newImage := record.Change.NewImage | |
| newImage = make(map[string]events.DynamoDBAttributeValue) | |
| // newImage["StoreID"] = events.NewStringAttribute("1") | |
| // newImage["SKU"] = events.NewStringAttribute("13") | |
| // newImage["Price"] = events.NewNumberAttribute("99") | |
| // logger.Sugar().Info(newImage) | |
| j, err := json.Marshal(newImage) | |
| if err != nil { | |
| logger.Sugar().Error(err.Error()) | |
| } | |
| var p Product | |
| err = json.Unmarshal(j, &p) | |
| if err != nil { | |
| logger.Sugar().Error(err.Error()) | |
| } | |
| // events. | |
| // data := Product{ | |
| // StoreID: "2", | |
| // SKU: "11", | |
| // // Tag: "New Arrival", | |
| // Price: 99, | |
| // // DiscountPrice: 89, | |
| // } | |
| // result, err := dynamodbattribute.MarshalMap(data) | |
| // if err != nil { | |
| // logger.Sugar().Error(err.Error()) | |
| // return | |
| // } | |
| // input := &dynamodb.PutItemInput{ | |
| // TableName: aws.String("Product-dev"), | |
| // Item: map[string]*dynamodb.AttributeValue{ | |
| // "StoreID": { | |
| // S: aws.String("1"), | |
| // }, | |
| // "SKU": { | |
| // S: aws.String("12"), | |
| // }, | |
| // "Price": { | |
| // N: aws.String("99"), | |
| // }, | |
| // }, | |
| // } | |
| // output, err := svc.PutItem(input) | |
| // if err != nil { | |
| // logger.Sugar().Error(err.Error()) | |
| // } | |
| // logger.Sugar().Info(output) | |
| } | |
| type Product struct { | |
| StoreID string // Hash key, a.k.a. partition key | |
| SKU string // Range key, a.k.a. sort key | |
| // Msg string `dynamo:"Message"` // Change name in the database | |
| Price int // Omits if zero value | |
| // Children []widget // Lists | |
| // Friends []string `dynamo:",set"` // Sets | |
| // Set map[string]struct{} `dynamo:",set"` // Map sets, too! | |
| Tag string `dynamo:",omitempty"` // Ignored | |
| } | |
| type ProductEvent interface { | |
| Execute(Product, map[string]events.DynamoDBAttributeValue) Product | |
| } | |
| type UpdatePrice struct { | |
| } | |
| func (a *UpdatePrice) Execute(state Product, event map[string]events.DynamoDBAttributeValue) Product { | |
| logger.Sugar().Info("execute UpdatePrice function", event) | |
| return state | |
| } | |
| type AddTag struct { | |
| } | |
| func (a *AddTag) Execute(state Product, event map[string]events.DynamoDBAttributeValue) Product { | |
| logger.Sugar().Info("execute AddTag function", event) | |
| return state | |
| } | |
| // func aggregate(state Product, event ProductEvent) (Product, error) { | |
| // return state, nil | |
| // } | |
| var eventMap map[string]ProductEvent | |
| var db *dynamo.DB | |
| func init() { | |
| cfg := zap.NewDevelopmentConfig() | |
| // cfg.Level.SetLevel(zap.InfoLevel) | |
| logger, _ = cfg.Build() | |
| session := session.Must(session.NewSessionWithOptions(session.Options{ | |
| SharedConfigState: session.SharedConfigEnable, | |
| })) | |
| db = dynamo.New(session) | |
| svc = dynamodb.New(session) | |
| eventMap = make(map[string]ProductEvent) | |
| eventMap["UpdatePrice"] = &UpdatePrice{} | |
| eventMap["AddTag"] = &AddTag{} | |
| } | |
| func handleRequest(ctx context.Context, request events.DynamoDBEvent) (events.APIGatewayProxyResponse, error) { | |
| logger.Sugar().Info("run lambda") | |
| for _, item := range request.Records { | |
| logger.Sugar().Info(item) | |
| logger.Sugar().Info(item.Change.NewImage) | |
| if event, ok := item.Change.NewImage["Event"]; ok { | |
| e := event.Map() | |
| // get type, StoreID, SKU, UID | |
| // get prevState from Product-dev table | |
| // get event handler from eventMap | |
| // execute -> newState | |
| // increment version field | |
| // put newState -> Product-dev | |
| // eventMap[] | |
| // if eventType, ok := e["type"]; ok { | |
| // if pe, ok := eventMap[eventType.String()]; ok { | |
| // var prevState Product | |
| // newState := pe.Execute(prevState, e) | |
| // logger.Sugar().Info(newState) | |
| // } | |
| // } | |
| // for k, v := range e { | |
| // _ = v | |
| // switch k { | |
| // case "type": | |
| // eventType = v.String() | |
| // } | |
| // } | |
| } | |
| // logger.Sugar().Info(eventType) | |
| } | |
| // // tableName := os.Getenv("Product_Event_Store") | |
| // // fmt.Println("table name: ", tableName) | |
| // // fmt.Println("ConnectionID: ", request.RequestContext.ConnectionID) | |
| // // fmt.Println("Headers:") | |
| // // for key, value := range request.Headers { | |
| // // fmt.Printf(" %s: %s\n", key, value) | |
| // // } | |
| // // type Data struct { | |
| // // UID string `json:"uid"` | |
| // // } | |
| // // data := Data{ | |
| // // UID: "123_1", | |
| // // } | |
| // // result, err := dynamodbattribute.MarshalMap(data) | |
| // // if err != nil { | |
| // // fmt.Println("Failed to marshall request") | |
| // // return events.APIGatewayProxyResponse{StatusCode: 500}, nil | |
| // // } | |
| // // var ExpressionAttributeNames map[string]*string | |
| // // ExpressionAttributeNames := make(map[string]*string) | |
| // // ExpressionAttributeNames["#val"] = aws.String("version") | |
| // // type Values struct { | |
| // // Incr int `json:":incr"` | |
| // // Zero int `json:":zero"` | |
| // // } | |
| // // val := Values{} | |
| // // ExpressionAttributeValues, err := dynamodbattribute.MarshalMap(val) | |
| // // if err != nil { | |
| // // fmt.Println("Failed to marshall request 2") | |
| // // return events.APIGatewayProxyResponse{StatusCode: 500}, nil | |
| // // } | |
| // input := &dynamodb.UpdateItemInput{ | |
| // TableName: aws.String("TestEventStore"), | |
| // // Key: result, | |
| // Key: map[string]*dynamodb.AttributeValue{ | |
| // "uid": { | |
| // S: aws.String("123"), | |
| // }, | |
| // "timestamp": { | |
| // S: aws.String(time.Now().Format(time.RFC3339)), | |
| // }, | |
| // }, | |
| // UpdateExpression: aws.String("SET version = if_not_exists(version, :zero) + :incr"), | |
| // // UpdateExpression: aws.String("SET #val = if_not_exists(#val, :zero) + :incr"), | |
| // // ExpressionAttributeNames: ExpressionAttributeNames, | |
| // // ExpressionAttributeValues: map[string]types.AttributeValue{ | |
| // // ":incr": &types.AttributeValueMemberN{Value: 1}, | |
| // // ":zero": &types.AttributeValueMemberN{Value: 0}, | |
| // // }, | |
| // ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{ | |
| // ":incr": { | |
| // N: aws.String("1"), | |
| // }, | |
| // ":zero": { | |
| // N: aws.String("0"), | |
| // }, | |
| // }, | |
| // // ExpressionAttributeValues: ExpressionAttributeValues, | |
| // ReturnValues: aws.String("NONE"), | |
| // } | |
| // _, err := svc.UpdateItem(input) | |
| // if err != nil { | |
| // fmt.Println("Failed to write to db", err) | |
| // } | |
| return events.APIGatewayProxyResponse{StatusCode: 200}, nil | |
| } | |
| func testPut() { | |
| table := db.Table("Product-dev") | |
| err := table.Put(Product{ | |
| StoreID: "4", | |
| SKU: "1", | |
| Price: 0, | |
| }).Run() | |
| if err != nil { | |
| logger.Sugar().Info(err.Error()) | |
| } | |
| } | |
| func main() { | |
| logger.Sugar().Info("Start") | |
| // createEvent() | |
| testPut() | |
| // lambda.Start(handleRequest) | |
| logger.Sugar().Info("Done") | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| build: | |
| go mod tidy | |
| GOOS=linux GOARCH=amd64 go build -o ./main ./main.go | |
| zip -j ./main.zip ./main | |
| rm ./main | |
| clean: | |
| rm main.zip | |
| rm main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment