Skip to content

Commit

Permalink
chore: update SDK settings
Browse files Browse the repository at this point in the history
  • Loading branch information
stainless-bot committed Jun 5, 2024
1 parent 65994d2 commit 520a519
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
10 changes: 10 additions & 0 deletions internal/apijson/decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,14 @@ func (d *decoderBuilder) typeDecoder(t reflect.Type) decoderFunc {
return f
}

func indirectUnmarshalerDecoder(n gjson.Result, v reflect.Value, state *decoderState) error {
return v.Addr().Interface().(json.Unmarshaler).UnmarshalJSON([]byte(n.Raw))
}

func unmarshalerDecoder(n gjson.Result, v reflect.Value, state *decoderState) error {
if v.Kind() == reflect.Pointer && v.CanSet() {
v.Set(reflect.New(v.Type().Elem()))
}
return v.Interface().(json.Unmarshaler).UnmarshalJSON([]byte(n.Raw))
}

Expand All @@ -135,6 +142,9 @@ func (d *decoderBuilder) newTypeDecoder(t reflect.Type) decoderFunc {
if !d.root && t.Implements(reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()) {
return unmarshalerDecoder
}
if !d.root && reflect.PointerTo(t).Implements(reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()) {
return indirectUnmarshalerDecoder
}
d.root = false

if _, ok := unionRegistry[t]; ok {
Expand Down
20 changes: 20 additions & 0 deletions internal/apijson/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,16 @@ func (t TypeB) IsKnown() bool {
return t == "b"
}

type UnmarshalStruct struct {
Foo string `json:"foo"`
prop bool `json:"-"`
}

func (r *UnmarshalStruct) UnmarshalJSON(json []byte) error {
r.prop = true
return UnmarshalRoot(json, r)
}

func (ComplexUnionTypeB) complexUnion() {}

func init() {
Expand Down Expand Up @@ -433,6 +443,16 @@ var tests = map[string]struct {
ComplexUnionStruct{Union: ComplexUnionTypeB{Baz: 12, Type: TypeB("b")}},
},

"unmarshal": {
`{"foo":"hello"}`,
&UnmarshalStruct{Foo: "hello", prop: true},
},

"array_of_unmarshal": {
`[{"foo":"hello"}]`,
[]UnmarshalStruct{{Foo: "hello", prop: true}},
},

"inline_coerce": {
`{"a":false,"b":237628372683,"c":654,"d":9999.43,"e":43.76,"f":[1,2,3,4]}`,
Inline{
Expand Down
2 changes: 1 addition & 1 deletion scripts/format
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ set -e
cd "$(dirname "$0")/.."

echo "==> Running gofmt -s -w"
gofmt -s -w ./...
gofmt -s -w .

0 comments on commit 520a519

Please sign in to comment.