hmdevno
hmdevno

Reputation: 129

How to unmarshal map[string]*dynamodb.AttributeValue?

I am querying a DynamoDB table and need to UnmarshalMap i.e. query output. The record in a table is JSON.

[{"movie":"Joker","year":"2019"}]

Or something like this

[{"movie":"Joker","year":"2019"}, {"movie":"Cruella","year":"2021"}]
type Movies struct {
   Movie string `json:"movie" bson:"movie" dynamodbav:"movie"`   
   Year  string `json:"year" bson:"year" dynamodbav:"year"`   
}

type Database struct {
    User    string    `json:"user" bson:"user" dynamodbav:"user"`   
    List    []*Movies `json:"movies" bson:"movies" dynamodbav:"movies"`
    
}


listOfMovies = Database{}

if err := dynamodbattribute.UnmarshalMap(tableOutput.Item, &listOfMovies); err != nil {
        log.Println(err)
        return nil, err
    }
return listOfMovies.List, nil

tableOutput.Item is a map and contains a record from database, I get no errors but the list of Movies is empty. I don't understand what I am doing wrong. Is this how UnmarshalMap should work?

Upvotes: 2

Views: 1809

Answers (1)

ossan
ossan

Reputation: 1855

To manage your scenario, I wrote down a trivial sample program to give you an overview of the writing and reading process. Below you can find the code for my sample application:

package main

import (
    "context"
    "encoding/json"
    "fmt"

    "dynamodbmovie/utils"

    "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"
    "github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

var cfg *aws.Config

func main() {
    cfg, _ = utils.GetAwsConfig()
    dynaClient := dynamodb.NewFromConfig(*cfg)

    // create table
    dynaClient.CreateTable(context.TODO(), &dynamodb.CreateTableInput{
        TableName: aws.String("movies"),
        AttributeDefinitions: []types.AttributeDefinition{
            {
                AttributeName: aws.String("user"),
                AttributeType: types.ScalarAttributeTypeS,
            },
        },
        KeySchema: []types.KeySchemaElement{
            {
                AttributeName: aws.String("user"),
                KeyType:       types.KeyTypeHash,
            },
        },
        BillingMode: types.BillingModePayPerRequest,
    })

    defer func() {
        dynaClient.DeleteTable(context.TODO(), &dynamodb.DeleteTableInput{
            TableName: aws.String("movies"),
        })
    }()

    // load table
    dynaClient.PutItem(context.TODO(), &dynamodb.PutItemInput{
        TableName: aws.String("movies"),
        Item: map[string]types.AttributeValue{
            "user":        &types.AttributeValueMemberS{Value: "user1"},
            "movies_list": &types.AttributeValueMemberS{Value: `[{"movie":"Joker","year":"2019"}, {"movie":"Cruella","year":"2021"}]`},
        },
    })

    // read table
    var filmString string
    res, _ := dynaClient.GetItem(context.TODO(), &dynamodb.GetItemInput{
        TableName: aws.String("movies"),
        Key: map[string]types.AttributeValue{
            "user": &types.AttributeValueMemberS{Value: "user1"},
        },
    })

    attributevalue.Unmarshal(res.Item["movies_list"], &filmString)
    myDb := &Database{
        User: "user1",
    }

    json.Unmarshal([]byte(filmString), &myDb.List)

    fmt.Println(len(myDb.List))
}

utils/models.go

package main

type Movies struct {
    Movie string `json:"movie"`
    Year  string `json:"year"`
}

type Database struct {
    User string    `json:"user"`
    List []*Movies `json:"movies"`
}

As you can see, there is no need for other tag annotation except the json ones. To accomplish your needs, I stored in DynamoDb the list of movies as a JSON string so you've to marshal/unmarshal to and from a string which is easy. Then, with a second unmarshal you can bring the information on the Database struct.

Please note, that for the sake of example, I didn't take into consideration the error management and the principles for writing good software.

Upvotes: 1

Related Questions