acmoune
acmoune

Reputation: 3411

How to manage GraphQL query loop?

Let's say we have this GraphQL Schema:

gql`
  type Department {
    id: ID!
    name: String!
    programs(programId: ID): [Program]! # filter if an ID is provided
  }

  type Program {
    id: ID!
    name: String!
    department: Department
  }

  extend type Query {
    getDepartments: [Department]
  }
`

The [probable] issue here is that you can get into this loop:

{
  getDepartments {
    name
    programs(1) {
      name
      department {
        name
        program(1) {
          ...
        }
      }
    }
  }
}

I'm new to GraphQL so, first I would like to know if this is a problem ? I have that feeling but it might be OK.

I tried to use this alternative:

gql`
  type Department {
    id: ID!
    name: String!
    programs(programId: ID): [Program] # filter if an ID is provided
  }

  type Program {
    id: ID!
    name: String!
  }

  extend type Query {
    getDepartments: [Department]
    getDepartmentForProgram(programId: ID!): Department
  }
`

With this, children can not get parents directly, it is now a top query. My second concern is to know if this is a good alternative, especially if the first one is a problem.

Thanks in advance.

Upvotes: 2

Views: 10234

Answers (1)

This is indeed a potential problem, in that a malicious user can create a very nested query that will hurt your backend. Apollo has a blog detailing this and other potential security concerns here.

As you can read there, there are solutions, for instance capping graphql queries depths, as shown here.

As far as I can tell, your solution is also valid - making queries work in only one way, and implementing the other programatically. The only issue being that it requires you to be diligent in expanding your schema, whereas more automatic solutions may require less attention once implemented (by securing you in runtime or providing tests to stop you from making mistakes).

Upvotes: 2

Related Questions