Lin Du
Lin Du

Reputation: 102672

graphql, split huge query to small queries

I am using https://developer.github.com/v4/

And I have a huge query like this:

query ($login: String!, $first: Int, $after: String) {
  user (login: $login){
    avatarUrl
    login
    name,
    followers(first: $first, after:$after) { 
      edges{
        cursor
        node{
          id
          name
          login
          avatarUrl
        }
      }
      totalCount
    },
    repositories(first: $first) {
      edges{
        cursor
        node{
          id
          name
        }
      }
      totalCount
    }
  }
}

But I think it's bad to query huge data from server.

I have followers and repositories pages. So I think split this huge query to small queries is better.

Here is small queries:

followers query:

query($login: String!, $first: Int, $after: String) {
    user(login: $login) {
      followers(first: $first, after: $after) {
        edges {
          cursor
          node {
            id
            name
            login
            avatarUrl
          }
        }
        totalCount
      }
    }
  }

repositories query:

query($login: String!, $first: Int, $after: String) {
    user(login: $login) {
      repositories(first: $first, after: $after) {
        nodes {
          id
          name
        }
        totalCount
      }
    }
  }

user query:

query($login: String!, $first: Int) {
    user(login: $login) {
      avatarUrl
      login
      name
    }
  }

Am I correctly? Is it necessary to do this? What's the best practice this situation? Is there any documentation for teaching people how to handle this or told people the best practice?

Upvotes: 3

Views: 4228

Answers (1)

Marco Daniel
Marco Daniel

Reputation: 5765

You can spit your queries into Fragments and in that way you would still only trigger one request and have smaller "queries". Something like this:

Fragment for followers:

fragment followers on User {
    followers(first: $first, after: $after) { 
      edges{
        cursor
        node{
          id
          name
          login
          avatarUrl
        }
      }
      totalCount
    },
}

Fragment for repositories:

fragment repositories on User {
  repositories(first: $first) {
      edges{
        cursor
        node{
          id
          name
        }
      }
      totalCount
    }
}

Put them all together in the query:

query ($login: String!, $first: Int, $after: String) {
  user (login: $login){
    avatarUrl
    login
    name
    ...followers
    ...repositories
  }
}

Upvotes: 5

Related Questions