Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating graphql schema with circular references

By using graphql-js, I need to create graphql schema dynamically by iterating over array of some data, for example:

[{
    name: 'author',
    fields: [{
        field: 'name'
    }, {
        field: 'books',
        reference: 'book'
    }]
}, {
    name: 'book',
    fields: [{
        field: 'title'
    }, {
        field: 'author',
        reference: 'author'
    }]
}]

The problem is circular references. When I'm creating AuthorType I need BookType to be already created and vise versa.

So resulting schema should look like:

type Author : Object {  
  id: ID!
  name: String,
  books: [Book]
}

type Book : Object {  
  id: ID!
  title: String
  author: Author
}

How can I solve this?

like image 417
User Created Image Avatar asked Aug 31 '16 18:08

User Created Image


1 Answers

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

like image 172
LordDave Avatar answered Sep 20 '22 23:09

LordDave