Skip to content

Commit

Permalink
Fix omitted model value for polyrelation fields
Browse files Browse the repository at this point in the history
  • Loading branch information
brandonc committed Nov 15, 2023
1 parent 960294d commit bb4d09f
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
31 changes: 31 additions & 0 deletions request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -734,6 +734,37 @@ func Test_UnmarshalPayload_polymorphicRelations_no_choice(t *testing.T) {
}
}

func Test_UnmarshalPayload_polymorphicRelations_omitted(t *testing.T) {
type pointerToOne struct {
ID string `jsonapi:"primary,blogs"`
Title string `jsonapi:"attr,title"`
Hero *OneOfMedia `jsonapi:"polyrelation,hero-media"`
}

in := bytes.NewReader([]byte(`{
"data": {
"type": "blogs",
"id": "3",
"attributes": {
"title": "Hello, World"
}
}
}`))
out := new(pointerToOne)

if err := UnmarshalPayload(in, out); err != nil {
t.Fatal(err)
}

if out.Title != "Hello, World" {
t.Errorf("expected Title %q but got %q", "Hello, World", out.Title)
}

if out.Hero != nil {
t.Fatalf("expected Hero to be nil, but got %+v", out.Hero)
}
}

func Test_choiceStructMapping(t *testing.T) {
cases := []struct {
val reflect.Type
Expand Down
7 changes: 6 additions & 1 deletion response.go
Original file line number Diff line number Diff line change
Expand Up @@ -417,8 +417,13 @@ func visitModelNode(model interface{}, included *map[string]*Node,
if choiceValue.IsNil() {
fieldValue = reflect.ValueOf(nil)
}

structValue := choiceValue.Elem()

// Short circuit if field is omitted from model
if !structValue.IsValid() {
break
}

if found, err := selectChoiceTypeStructField(structValue); err == nil {
fieldValue = found
}
Expand Down
12 changes: 12 additions & 0 deletions response_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,18 @@ func TestMarshalPayloadWithHasOneNilPolyrelation(t *testing.T) {
}
}

func TestMarshalPayloadWithHasOneOmittedPolyrelation(t *testing.T) {
blog := &BlogPostWithPoly{
ID: "1",
Title: "Hello, World",
}

out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, blog); err != nil {
t.Fatalf("expected no error but got %s", err)
}
}

func TestMarshalPayloadWithHasOneNilRelation(t *testing.T) {
blog := &Blog{
ID: 1,
Expand Down

0 comments on commit bb4d09f

Please sign in to comment.