Skip to content

Commit

Permalink
automatically omit nil ptr of value types with custom encoding (fixes #…
Browse files Browse the repository at this point in the history
  • Loading branch information
guregu committed Jul 15, 2019
1 parent 41f0249 commit cc063bc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
21 changes: 20 additions & 1 deletion encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,15 +105,34 @@ func Marshal(v interface{}) (*dynamodb.AttributeValue, error) {
}

func marshal(v interface{}, special string) (*dynamodb.AttributeValue, error) {
rv := reflect.ValueOf(v)
switch x := v.(type) {
case *dynamodb.AttributeValue:
return x, nil
case Marshaler:
if rv.Kind() == reflect.Ptr && rv.IsNil() {
if _, ok := rv.Type().Elem().MethodByName("MarshalDynamo"); ok {
// MarshalDynamo is defined on value type, but this is a nil ptr
return nil, nil
}
}
return x.MarshalDynamo()
case dynamodbattribute.Marshaler:
if rv.Kind() == reflect.Ptr && rv.IsNil() {
if _, ok := rv.Type().Elem().MethodByName("MarshalDynamoDBAttributeValue"); ok {
// MarshalDynamoDBAttributeValue is defined on value type, but this is a nil ptr
return nil, nil
}
}
av := &dynamodb.AttributeValue{}
return av, x.MarshalDynamoDBAttributeValue(av)
case encoding.TextMarshaler:
if rv.Kind() == reflect.Ptr && rv.IsNil() {
if _, ok := rv.Type().Elem().MethodByName("MarshalText"); ok {
// MarshalText is defined on value type, but this is a nil ptr
return nil, nil
}
}
text, err := x.MarshalText()
if err != nil {
return nil, err
Expand All @@ -125,7 +144,7 @@ func marshal(v interface{}, special string) (*dynamodb.AttributeValue, error) {
case nil:
return nil, nil
}
return marshalReflect(reflect.ValueOf(v), special)
return marshalReflect(rv, special)
}

var nilTm encoding.TextMarshaler
Expand Down
6 changes: 6 additions & 0 deletions encoding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ package dynamo
import (
"encoding"
"strconv"
"time"

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

const (
Expand Down Expand Up @@ -211,6 +213,10 @@ var itemEncodingTests = []struct {
EmptyM map[string]bool
EmptyPtr *int
EmptyIface interface{}
NilTime *time.Time
NilCustom *customMarshaler
NilText *textMarshaler
NilAWS *dynamodbattribute.UnixTime
}{
OK: "OK",
EmptyL: []int{},
Expand Down

0 comments on commit cc063bc

Please sign in to comment.