Skip to content Skip to sidebar Skip to footer

Graphql Fields As A Function

I am studying GraphQL and I get a bit confused from different implementations on the specific issue when writing the fields of a GraphQLObjectType. What is the difference between t

Solution 1:

When you need to make a circular reference.

Look for my similiar answer here

Dynamically creating graphql schema with circular references

Solution 2:

This is a great example of CLOSURE. Imagine you have two types in a file and they are referencing each other.

constBookType= newGraphQLObjectType({
    name: 'BookType',
    fields: {  // as objectauthor: {
        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

constAuthorType= newGraphQLObjectType({
    name: 'AuthorType',
    fields: {  // as objectbooks: {
        type: newGraphQLList(BookType), //one author might have multiple booksresolve: (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 isnot defined

to circumvent this, we turn fields to a function. this function is a CLOSURE function. this is a great example why closures are so helpful.

When js engine reads the file first, it saves all the variables that are referenced inside of a function into memory heap as a closure storage of that function. All the variables that BookType.fields need are stored into the closure environment of the BookType.fields(). So now if javascript executes the Booktype.fields(), it checks if "AuthorType" is defined inside the function, it is not defined so it checks its closure storage, AuthorType was already stored there in the beginning, so it uses it.

Post a Comment for "Graphql Fields As A Function"