Skip to content

Commit bb4d09f

Browse files
committed
Fix omitted model value for polyrelation fields
1 parent 960294d commit bb4d09f

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

request_test.go

+31
Original file line numberDiff line numberDiff line change
@@ -734,6 +734,37 @@ func Test_UnmarshalPayload_polymorphicRelations_no_choice(t *testing.T) {
734734
}
735735
}
736736

737+
func Test_UnmarshalPayload_polymorphicRelations_omitted(t *testing.T) {
738+
type pointerToOne struct {
739+
ID string `jsonapi:"primary,blogs"`
740+
Title string `jsonapi:"attr,title"`
741+
Hero *OneOfMedia `jsonapi:"polyrelation,hero-media"`
742+
}
743+
744+
in := bytes.NewReader([]byte(`{
745+
"data": {
746+
"type": "blogs",
747+
"id": "3",
748+
"attributes": {
749+
"title": "Hello, World"
750+
}
751+
}
752+
}`))
753+
out := new(pointerToOne)
754+
755+
if err := UnmarshalPayload(in, out); err != nil {
756+
t.Fatal(err)
757+
}
758+
759+
if out.Title != "Hello, World" {
760+
t.Errorf("expected Title %q but got %q", "Hello, World", out.Title)
761+
}
762+
763+
if out.Hero != nil {
764+
t.Fatalf("expected Hero to be nil, but got %+v", out.Hero)
765+
}
766+
}
767+
737768
func Test_choiceStructMapping(t *testing.T) {
738769
cases := []struct {
739770
val reflect.Type

response.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -417,8 +417,13 @@ func visitModelNode(model interface{}, included *map[string]*Node,
417417
if choiceValue.IsNil() {
418418
fieldValue = reflect.ValueOf(nil)
419419
}
420-
421420
structValue := choiceValue.Elem()
421+
422+
// Short circuit if field is omitted from model
423+
if !structValue.IsValid() {
424+
break
425+
}
426+
422427
if found, err := selectChoiceTypeStructField(structValue); err == nil {
423428
fieldValue = found
424429
}

response_test.go

+12
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,18 @@ func TestMarshalPayloadWithHasOneNilPolyrelation(t *testing.T) {
167167
}
168168
}
169169

170+
func TestMarshalPayloadWithHasOneOmittedPolyrelation(t *testing.T) {
171+
blog := &BlogPostWithPoly{
172+
ID: "1",
173+
Title: "Hello, World",
174+
}
175+
176+
out := bytes.NewBuffer(nil)
177+
if err := MarshalPayload(out, blog); err != nil {
178+
t.Fatalf("expected no error but got %s", err)
179+
}
180+
}
181+
170182
func TestMarshalPayloadWithHasOneNilRelation(t *testing.T) {
171183
blog := &Blog{
172184
ID: 1,

0 commit comments

Comments
 (0)