javascriptrequestgraphqlrelayrelaymodern

How to decrease request numbers with GraphQL mutations?


I want to decrease number of requests to graphql server. I have objects in an array like

 [{name: "gokhan", age: 20}, ...];

I use graphql a mutation to add every item of an array.

If The array has 50 items, I need to send 50 requests to add all data. Is there any way to decrease the number of requests?


Solution

  • There's two main options to solve this:

    Option 1 (preferred): add a new mutation to your GraphQL schema that handles a GraphQLList of these input objects. How you'd do this would change depending on what GraphQL server you're using (in PostGraphile you'd use a custom mutation or schema extension); but the Schema Definition Language might look like this:

    input CreateManyPeopleInput {
      people: [CreatePersonInput!]!
    }
    
    type CreateManyPeoplePayload {
      createdPeople: [Person!]
    }
    
    extend type Mutation {
      createManyPeople(input: CreateManyPeopleInput): CreateManyPeoplePayload
    }
    

    Option 2: enable "query batching". To use this, you will need both a server and a client that support GraphQL Query Batching. Essentially it allows you to send multiple GraphQL queries in one request and get all the responses in one response. This doesn't require any changes to your GraphQL schema, but it won't be as efficient and typical implementations only allow batching ~10 queries into one request so your 50 creates might still require 5 requests.