Skip to content

Commit

Permalink
add nil pointer test
Browse files Browse the repository at this point in the history
  • Loading branch information
aacebo committed Dec 2, 2024
1 parent 37e2ca9 commit 328a83b
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
8 changes: 8 additions & 0 deletions gq/pointer.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ func (self Pointer) Key() string {
func (self Pointer) Do(params *DoParams) Result {
value := reflect.ValueOf(params.Value)

if value.Kind() == reflect.Pointer && value.IsNil() {
return Result{}
}

if value.Kind() == reflect.Pointer {
value = value.Elem()
params.Value = nil
Expand All @@ -41,6 +45,10 @@ func (self Pointer) Do(params *DoParams) Result {
func (self Pointer) Resolve(params *ResolveParams) Result {
value := reflect.ValueOf(params.Value)

if value.Kind() == reflect.Pointer && value.IsNil() {
return Result{}
}

if value.Kind() == reflect.Pointer {
value = value.Elem()
params.Value = nil
Expand Down
41 changes: 41 additions & 0 deletions gq/pointer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,47 @@ func TestPointer(t *testing.T) {
}
})

t.Run("should resolve nil struct field as pointer", func(t *testing.T) {
type User struct {
Name string `json:"name"`
Email *string `json:"email"`
}

schema := gq.Object[User]{
Name: "User",
Fields: gq.Fields{
"name": gq.Field{Type: gq.String{}},
"email": gq.Field{Type: gq.Pointer{Type: gq.String{}}},
},
}

res := schema.Do(&gq.DoParams{
Query: "{name,email}",
Value: User{
Name: "test",
Email: nil,
},
})

if res.Error != nil {
t.Fatal(res.Error)
}

user, ok := res.Data.(User)

if !ok {
t.Fatal(res.Data)
}

if user.Name != "test" {
t.Fatalf("expected `%s`, received `%s`", "test", user.Name)
}

if user.Email != nil {
t.Fatalf("expected `nil`, received `%s`", *user.Email)
}
})

t.Run("should json", func(t *testing.T) {
schema := gq.Pointer{gq.String{}}
b, _ := json.Marshal(schema)
Expand Down

0 comments on commit 328a83b

Please sign in to comment.