DEV Community

Cover image for Make sure your GraphQL Lists return predictable results!
Soney Mathew
Soney Mathew

Posted on • Updated on

Make sure your GraphQL Lists return predictable results!

Home page of https://graphql.org/ states this fact

Describe your data

type Query {
 company(name: String): Company
}
type User {
  name: String
}
type Company {
  name: String
  tagline: String
  # List of board members
  boardMembers: [User] 
}

Ask for what you want

{
  company(name: "Acme") {
    name
    tagline
    boardMembers {
      name
    }
  }
}

Get predictable results

{
  "data": {
    "company": {
      "name": "Acme",
      "tagline": "Acme is all you need!",
      "boardMembers": [
        {
          "name": "Tom"
        },
        {
          "name": "Jerry"
        }
      ]
    }
  }
}

Are you sure? Are you sure you are getting predictable results?

This API is breaking a fundamental promise given by GraphQL! You simply are not getting predictable results!

As you scale the number of items returned by the list might become unpredictably large. See the image below for example, there is no predictability in the size of items returned in the list

Unpredictable size of the list

Give the control back to the client, always set limits. Let the client decide how much they want to fetch.

type Company {
  name: String
  tagline: String
  # List of board members
  boardMembers(first:Int) : [User] 
}

Now client can limit the query results to exactly how much they need

{
  company(name: "Acme") {
    name
    tagline
    boardMembers(first:3) {
      name
    }
  }
}

Refer: https://graphql.org/learn/pagination/#slicing

🙏

Top comments (2)

Collapse
 
itsjzt profile image
Saurabh Sharma

One thing I would like to mention [User] means the array can contain null or even the whole thing could be null instead of array.

Collapse
 
soneymathew profile image
Soney Mathew

That's very true and a good practice to follow.
I observed that a type safe implementation ensures that client is equipped to use that knowledge and handle those cases explicitly, so I considered it predictable behaviour.