diff --git a/connector/api/decimal.go b/connector/api/decimal.go index f7fe1cf..c3e0990 100644 --- a/connector/api/decimal.go +++ b/connector/api/decimal.go @@ -20,7 +20,7 @@ type Decimal struct { func NewDecimal[T comparable](value T) (Decimal, error) { result := Decimal{} if err := result.FromValue(value); err != nil { - return Decimal{}, nil + return Decimal{}, err } return result, nil } @@ -50,7 +50,7 @@ func (bi Decimal) MarshalJSON() ([]byte, error) { func (bi *Decimal) UnmarshalJSON(b []byte) error { var value any if err := json.Unmarshal(b, &value); err != nil { - return err + return fmt.Errorf("invalid decimal value: %s", err) } return bi.FromValue(value) diff --git a/connector/api/decimal_test.go b/connector/api/decimal_test.go new file mode 100644 index 0000000..b50d43f --- /dev/null +++ b/connector/api/decimal_test.go @@ -0,0 +1,30 @@ +package api + +import ( + "encoding/json" + "testing" + + "github.com/hasura/ndc-sdk-go/utils" + "gotest.tools/v3/assert" +) + +func TestDecimal(t *testing.T) { + assert.Assert(t, Decimal{}.IsNil()) + assert.Equal(t, Decimal{}.String(), "Inf") + assert.Equal(t, Decimal{value: utils.ToPtr(1.2)}.String(), "1.2") + + _, err := NewDecimal("foo") + assert.ErrorContains(t, err, "failed to convert Float, got: foo") + + dec, err := NewDecimal("1.1") + assert.NilError(t, err) + assert.Equal(t, dec.ScalarName(), "Decimal") + assert.Equal(t, dec.String(), "1.1") + + assert.ErrorContains(t, json.Unmarshal([]byte("foo"), &dec), "invalid character") + assert.NilError(t, json.Unmarshal([]byte("2.2"), &dec)) + + bs, err := json.Marshal(dec) + assert.NilError(t, err) + assert.Equal(t, string(bs), `"2.2"`) +}