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 referencingAuthorType
. Now imagine you haveAuthorType
defined underBookType
referencingBookType
,
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 thatfields.author.type
isAuthorType
andAuthorType
is not defined above. So it will givereference 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?