2

I have this code:

const ProductType = new GraphQLObjectType({
    name: 'Product',
    fields: {
        id: { type: GraphQLID },
        name: { type: GraphQLString },
        category: {
            type: CategoryType,
            resolve: async (parent) => {
                return await Category.findOne({_id: parent.category});
            }
        }
    }
});

const CategoryType = new GraphQLObjectType({
    name: 'Category',
    fields: {
        id: { type: GraphQLID },
        name: { type: GraphQLString },
        products: {
            type: ProductType,
            resolve: async (parent, args) => {
                return await Product.find({category: parent._id});
            }
        }
    }
});

const Query = new GraphQLObjectType({
    name: 'Query',
    fields: {
        Categories: {
            type: new GraphQLList(CategoryType),
            resolve: async () => {
                return await Category.find();
            }
        }
    }
});

When i try to compile i get ReferenceError: Cannot access 'CategoryType' before initialization. I understand that first of all I should declare and only after that use, but I saw a similar code in one lesson on YouTube, and I think that it should work, but it’s not.

1 Answers1

5

fields can take a function instead of an object. This way the code inside the function won't be evaluated immediately:

fields: () => ({
  id: { type: GraphQLID },
  name: { type: GraphQLString },
  category: {
    type: CategoryType,
    resolve: (parent) => Category.findOne({_id: parent.category}),
  }
})
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • Could you please let me know, which is faster the above code or using buildSchema or graphql-tools ? – Muhammad Nov 03 '20 at 15:21
  • @Muhammad Your schema will only be built once when you first start your server. Any differences in speed between these different approaches are negligible and will not impact the rate at which your server is able to process requests. – Daniel Rearden Nov 03 '20 at 17:08
  • thank you very much, please let me know, would you suggest us to use `graphql-tools` for schema language ? or it is better we use like javascript functions `fields(), resovle` as here exist in this code ??? and is `graphql-tools` developed by Facebook ? – Muhammad Nov 04 '20 at 08:34