Dynamically creating graphql schema with circular references

假如想象 提交于 2019-12-01 09:03:47
LordDave

Quoted from official documentation

http://graphql.org/docs/api-reference-type-system/

When two types need to refer to each other, or a type needs to refer to itself in a field, you can use a function expression (aka a closure or a thunk) to supply the fields lazily.

var AddressType = new GraphQLObjectType({
  name: 'Address',
  fields: {
    street: { type: GraphQLString },
    number: { type: GraphQLInt },
    formatted: {
      type: GraphQLString,
      resolve(obj) {
        return obj.number + ' ' + obj.street
      }
    }
  }
});

var PersonType = new GraphQLObjectType({
  name: 'Person',
  fields: () => ({
    name: { type: GraphQLString },
    bestFriend: { type: PersonType },
  })
});

Also look at this related answer of circular Category-Subcategory types

I solved this problem by using a thunk for the fields field.

const User = new GraphQLObjectType({
  name: 'User',
  fields: () => ({
    id: { type: GraphQLID }
  })
});

When you make your fields a thunk rather than an object literal you can use types that are defined later in the file.

Please see this post for more info Is there a way to avoid circular type dependencies in GraqhQL?

Based on that post I think this is the correct way to do it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!