Skip to content

Commit

Permalink
service/dynnamodb/dynamodbattribute: use json number in decoder, add …
Browse files Browse the repository at this point in the history
…tests
  • Loading branch information
aavshr committed Oct 12, 2021
1 parent ae0f9b8 commit 264bd9a
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
7 changes: 7 additions & 0 deletions service/dynamodb/dynamodbattribute/decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,9 @@ type Decoder struct {
// Number type instead of float64 when the destination type
// is interface{}. Similar to encoding/json.Number
UseNumber bool

// Instructs the decoder to use Json Number
UseJsonNumber bool
}

// NewDecoder creates a new Decoder with default configuration. Use
Expand Down Expand Up @@ -371,6 +374,10 @@ func (d *Decoder) decodeNumber(n *string, v reflect.Value, fieldTag tag) error {
}

func (d *Decoder) decodeNumberToInterface(n *string) (interface{}, error) {
if d.UseJsonNumber {
return json.Number(*n), nil
}

if d.UseNumber {
return Number(*n), nil
}
Expand Down
31 changes: 31 additions & 0 deletions service/dynamodb/dynamodbattribute/decode_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dynamodbattribute

import (
"encoding/json"
"fmt"
"reflect"
"strconv"
Expand Down Expand Up @@ -504,6 +505,36 @@ func TestDecodeUseNumber(t *testing.T) {
}
}

func TestDecodeUseJsonNumber(t *testing.T) {
u := map[string]interface{}{}
av := &dynamodb.AttributeValue{
M: map[string]*dynamodb.AttributeValue{
"abc": {S: aws.String("value")},
"def": {N: aws.String("123")},
"ghi": {BOOL: aws.Bool(true)},
},
}

decoder := NewDecoder(func(d *Decoder) {
d.UseJsonNumber = true
})
err := decoder.Decode(av, &u)
if err != nil {
t.Errorf("expect no error, got %v", err)
}

if e, a := "value", u["abc"]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
n := u["def"].(json.Number)
if e, a := "123", n.String(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := true, u["ghi"]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}

func TestDecodeUseNumberNumberSet(t *testing.T) {
u := map[string]interface{}{}
av := &dynamodb.AttributeValue{
Expand Down
5 changes: 5 additions & 0 deletions service/dynamodb/dynamodbattribute/marshaler_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dynamodbattribute

import (
"encoding/json"
"math"
"reflect"
"testing"
Expand Down Expand Up @@ -77,6 +78,10 @@ var marshalerScalarInputs = []marshallerTestInput{
input: Number("12"),
expected: &dynamodb.AttributeValue{N: aws.String("12")},
},
{
input: json.Number("456"),
expected: &dynamodb.AttributeValue{N: aws.String("456")},
},
{
input: simpleMarshalStruct{},
expected: &dynamodb.AttributeValue{
Expand Down

0 comments on commit 264bd9a

Please sign in to comment.