apollo-server icon indicating copy to clipboard operation
apollo-server copied to clipboard

set depth in nested graphql quries

Open KhalilMeziane opened this issue 2 years ago • 1 comments

Issue Description

How i can prevent is drilling?

Implementing Federated GraphQL using Apollo Federation: i have this query:

query Query {
  reviews {
    user {
      reviews {
        user {
          reviews {
            user {
              reviews {
                user {
                  reviews {
                    user {
                      .....
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

This query is attempting to fetch reviews and the associated user information recursively. However, it leads to excessive nesting, making the query less efficient and potentially causing performance issues. and this is review schema =

gql`
    type Review {
        id: ID
        rating: Float
        content: String
        productId: ID
        userId: ID
        user: User
    }

    extend type User @key(fields: "id"){
        id: ID @external
        reviews: [Review]
    }

    extend type Product @key(fields: "id"){
        id: ID @external
        reviews: [Review]
    }

    type Query @extends {
        reviews: [Review]!
        review(id: ID!): Review!
    }
` 

and user schema:

gql`
    type User @key(fields: "id") {
        id: ID!
        email: String
        username: String
    }

    extend type Query {
        users: [User]!
        user(id: ID!): User!
    }
`

Link to Reproduction


Reproduction Steps

No response

KhalilMeziane avatar Jul 12 '23 13:07 KhalilMeziane

It should work somehow like this, but I didn't tested it:

const { ApolloServer } = require("apollo-server");
const depthLimit = require("graphql-depth-limit");
const { typeDefs, resolvers } = require("./schema");
const server = new ApolloServer({
  typeDefs,
  resolvers,
  // Allow a maximum query depth of 2
  validationRules: [depthLimit(2)]
});

see: https://benhoneywill.com/protecting-your-graphql-server-from-dangerous-queries/

karladler avatar Mar 12 '24 14:03 karladler