Fetch deep nested documents with GraphQL

1.8k Views Asked by At

What would the best approach to fetch deep nested object with graphql only when asked for. I'm talking here performance wise

Lets say you have the following mongo/mongoose schema :

User 
  |
  |_ Name
  |
  |_ Friends (RefId into User)
      |
      |_ User
          |
          |_ Friends (RefId into User)

      .....

suppose each user has many friends who in turn have many other friends, how would decide how deeply you need to populate inside a resolve function?

the naive method of "just populating" might be harmful as many of the queries might just select the field name which is on the 0 level, but end up populating 1/2 of your db.

Thanks in advance.

1

There are 1 best solutions below

1
On BEST ANSWER

The best way will be to have the GraphQL client specify how deeply nested data it wants, i.e., having the client pass a parameter when it asks for friends of a user.

Using graphql npm package, the implementation looks like below:

const UserType = new GraphQLObjectType({
  name: 'NestedUser',
  fields: {
    ...
    ...
    friends: {
      type: new GraphQLList(UserType),
      args: {
        level: {
          type: GraphQLInt,
          defaultValue: 0,
        },
        ...connectionArgs,
      },
      resolve: (user, {level, ...args}) => {
        // Populate nestedFriends according to the level
        return nestedFriends;
      },
    },
  },
});