0

I've been studying graphql recently and I found out to implement a circular reference inside my schema, I need to declare my field property as a thunk or a function, referring this answer it helped me a lot to understand this.

If I may quote from that answer,

Imagine you have two types in a file and they are referencing each other.

const BookType= new GraphQLObjectType({ 
    name: 'BookType',
    fields: {  // as object -> not the correct implementation yet
      author: {
        type: AuthorType,
        
        resolve: (parentValue, args) => {
          // query the author based on your db implementation.
        }
      }
    }
  });

BookType has a field author and referencing AuthorType. Now imagine you have AuthorType defined under BookType referencing BookType,

const AuthorType= new GraphQLObjectType({
    name: 'AuthorType',
    fields: {  // as object
      books: {
        type: new GraphQLList(BookType), //one author might have multiple books
        
        resolve: (parentValue, args) => {
          // query the books based on your db implementation.
        }
      }
    }
  });

So when Javascript engine needs to use BookType it will see that fields.author.type is AuthorType and AuthorType is not defined above. So it will give reference error:AuthorType is not defined.

So the correct implementation of BookType would be,

const BookType= new GraphQLObjectType({ 
    name: 'BookType',
    fields: () => {  // as a thunk -> the correct implementation
      author: {
        type: AuthorType,

        resolve: (parentValue, args) => {
          // query the author based on your db implementation.
        }
      } 
    }
  });

What I need to know is defining the field property as a thunk, for circular references or for references of its own type, describes what usage of JavaScript.

Is it the hoisting or a closure or the both?

Clarke
  • 185
  • 10
  • 1
    Yes, [it's](https://stackoverflow.com/a/52880419/1048572) [both](https://stackoverflow.com/q/31219420/1048572) – Bergi May 28 '21 at 15:59
  • @Bergi can you explain why it is a usage of a closure. I see only the usage of hoisting ? – Clarke May 28 '21 at 16:18
  • 1
    The `() => {…}` function closes over the free variable `AuthorType`. – Bergi May 28 '21 at 16:19
  • @Bergi if there was no closures and only hoisting available in JavaScript, what would be the error – Clarke May 28 '21 at 16:22
  • @Bergi if there is hoisting only `AuthorType` will be available to `BookType`. so closure is not needed there – Clarke May 28 '21 at 16:29
  • 1
    If there were no [closures](https://stackoverflow.com/q/111102/1048572), calling the arrow function would complain about `Undeclared variable 'AuthorType'`, because it's neither a parameter nor defined inside the function. – Bergi May 28 '21 at 16:41
  • @Bergi thanks man now I got it. Thank you very much – Clarke May 28 '21 at 17:04

0 Answers0