Graphql: Creating objects with circular references between fields

Created on 2 May 2018  路  2Comments  路  Source: graphql-go/graphql

One of the nice thing about graphql is that it provides a sensible way to resolve cyclic references between objects. For example, if I have a many-to-many relationship between two object types House and Resident then I should be able to query either one from the other:

query {
  house(address: "foo") {
    residents {
      name
      age
    }
  }
}

or

query {
  resident(name: "bar") {
    houses {
      address
    }
  }
}

However, using this library, if I try to create two objects with such a circular reference then I get a panic:

hosueType := &graphql.Object{...}
residentType := &graphql.Object{...}

houseType.Fields["residents"] = &graphql.Field{Type: graphql.NewList(residentType)}
residentType.Fields["houses"] = &graphql.Field{Type: graphql.NewList(houseType)}

Can you give me an example of how to construct such circular dependencies with this library?

Most helpful comment

You could try using AddFieldConfig
https://godoc.org/github.com/graphql-go/graphql#Interface.AddFieldConfig

houseType := &graphql.Object{...}
residentType := &graphql.Object{...}

houseType.AddFieldConfig("residents", &graphql.Field{Type: graphql.NewList(residentType)})
residentType.AddFieldConfig("houses",  &graphql.Field{Type: graphql.NewList(houseType)})

All 2 comments

You could try using AddFieldConfig
https://godoc.org/github.com/graphql-go/graphql#Interface.AddFieldConfig

houseType := &graphql.Object{...}
residentType := &graphql.Object{...}

houseType.AddFieldConfig("residents", &graphql.Field{Type: graphql.NewList(residentType)})
residentType.AddFieldConfig("houses",  &graphql.Field{Type: graphql.NewList(houseType)})

Hello,
You can create circular dependencies at the initialization of your package

houseType := &graphql.Object{...}
residentType := &graphql.Object{...}

func init() {
    houseType.AddFieldConfig("residents",  &graphql.Field{Type: graphql.NewList(residentType)})
    residentType.AddFieldConfig("s",  &graphql.Field{Type: graphql.NewList(houseType)})
}

Was this page helpful?
0 / 5 - 0 ratings

Related issues

januszm picture januszm  路  6Comments

bbuck picture bbuck  路  4Comments

sogko picture sogko  路  6Comments

yhc44 picture yhc44  路  5Comments

sanae10001 picture sanae10001  路  5Comments