graphql-go / graphql-go/graphql

Dangerous issue about Go anonymous composition

Open
#553 1 comment 2 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
10.1k
Forks
845
PR merge metrics
No merged PRs in 30d

Description

I discovered this bug trying to resolve this problem https://github.com/graphql-go/graphql/issues/183#issuecomment-659317404 .

Essentially, this library does not allow to have **anonymous fields for compositions** since those fields are not evaluated.

**Example**
```go
type Car struct {
Speed int `json:"speed"`
Product
}

type Product struct {
Price int `json:"price"`
Description string `json:"description"`
}
```

**GraphQL schema**
```go
carType := graphql.NewObject(graphql.ObjectConfig{
Name: "Car",
Fields: graphql.Fields{
"speed": &graphql.Field{
Type: graphql.NewNonNull(graphql.Int),
},
"price": &graphql.Field{
Type: graphql.NewNonNull(graphql.Int),
},
"description": &graphql.Field{
Type: graphql.NewNonNull(graphql.String),
},
},
})
```

**Result**

The `price` and `description` fields has a `null` value for GraphQL library and this is not allowed since we declare a `graphql.NewNonNull` field. Indeed, we get the following error:

- `Cannot return null for non-nullable field price.`
- `Cannot return null for non-nullable field description.`

**Temporary solution**

The only way to fix this problem at the moment is to duplicate code:

```go
type Car struct {
Speed int `json:"speed"`
Price int `json:"price"`
Description string `json:"description"`
}

type Product struct {
Price int `json:"price"`
Description string `json:"description"`
}
```

Or changing a lot of things both internal and external (also the public fields to API consumers).

```go
type Car struct {
Speed int `json:"speed"`
Product Product `json:"product"`
}

type Product struct {
Price int `json:"price"`
Description string `json:"description"`
}
```

Instead of:
```graphql
{
speed
price
description
}
```

We have to provide this:
```graphql
{
speed
product {
price
description
}
}
```

Both solutions are really limited and go against clean code.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.