Skip to content

Commit

Permalink
Add test and docs for int workaround
Browse files Browse the repository at this point in the history
  • Loading branch information
Acconut committed Dec 30, 2021
1 parent 6ba2d3a commit b95d703
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
5 changes: 5 additions & 0 deletions assembly.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,14 @@ type FileInfo struct {
Meta map[string]interface{} `json:"meta"`
}

// Integer is a warpper around a normal int but has softer JSON parsing requirements.
// It can be used in situations where a JSON value is not always a number. Then parsing
// will not fail and a default value of 0 will be returned.
// For more details see: https://github.com/transloadit/go-sdk/issues/26
type Integer int

func (i *Integer) UnmarshalJSON(text []byte) error {
// Try parsing as an integer and default to 0, if it fails.
n, err := strconv.Atoi(string(text))
if err != nil {
*i = 0
Expand Down
31 changes: 31 additions & 0 deletions assembly_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package transloadit

import (
"encoding/json"
"fmt"
"os"
"strings"
Expand Down Expand Up @@ -232,3 +233,33 @@ func TestListAssemblies(t *testing.T) {
t.Fatal("wrong template name")
}
}

func TestInteger_MarshalJSON(t *testing.T) {
var info AssemblyInfo
err := json.Unmarshal([]byte(`{"bytes_expected":55}`), &info)
if err != nil {
t.Fatal(err)
}

if info.BytesExpected != 55 {
t.Fatal("wrong integer parsed")
}

err = json.Unmarshal([]byte(`{"bytes_expected":null}`), &info)
if err != nil {
t.Fatal(err)
}

if info.BytesExpected != 0 {
t.Fatal("wrong default value for null")
}

err = json.Unmarshal([]byte(`{"bytes_expected":""}`), &info)
if err != nil {
t.Fatal(err)
}

if info.BytesExpected != 0 {
t.Fatal("wrong default value for string")
}
}

0 comments on commit b95d703

Please sign in to comment.