graphql

How to sustain potentially infinite Graphql queries?


There's one thing I have never understood about Graphql. I think I'll paint by problem by giving some examples.

Let's say I have an Account type and a Chat type. An Account can have multiple Chats associated with it, but a Chat can only be associated with a single Account. The schema might look something like this:

type Account {
  id: String!
  username: String!
  chats: [Chat!]!
}

type Chat {
  id: String!
  text: String!
  account: Account!
}

Let's say I am exposing the following queries:

type Query {
  account(id: String!): Account
  accounts: [Account!]!
}

Now, I will query my schema:

accounts {
  id
  username
  chats {
    id
    text
  }
}

This is a pretty straigthforward query - I simply what to grab all the chats by all the accounts.

But what if I have a deeper query like this:

accounts {
  id
  username
  chats {
    id
    text
    account {
      id
      username
      chats {
        id
        text
      }
    }
  }
}

I know that in reality, querying this data would be ridiculous, but still, it should be possible, right?

Now let's switch our view from the consumer of the API to the actual developer of the API. How is the graphql developer meant to sustain these, potentially, infinite queries? Does Graphql resolve these automatically (it doesn't seem to)? Or am I just missing something out?

Thanks for any help.


Solution

  • How is the graphql developer meant to sustain these, potentially, infinite queries?

    Not possible in having "infinite" nested queries.

    GraphQL schema should be acyclic - meaning the relationships between types should be unidirectional.

    Just a rule that the schema should be based on the query patterns in the client application.

    So having a nested account within the chat would simply mean the use case and sequence are not properly defined.