How to send array of objects with graphql mutation?

Member

by daisha , in category: Javascript , 4 months ago

How to send array of objects with graphql mutation?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 4 months ago

@daisha 

To send an array of objects with a GraphQL mutation, you can define a custom input type in your schema that represents the array of objects. Here's an example of how you could achieve this:

  1. Define the custom input type in your GraphQL schema:
1
2
3
4
5
6
7
8
9
input ObjectInput {
  id: ID!
  name: String!
  // Add any other fields needed for the object
}

input ArrayOfObjectsInput {
  objects: [ObjectInput!]!
}


  1. Use the custom input type in your mutation:
1
2
3
type Mutation {
  createObjects(objects: ArrayOfObjectsInput!): [Object!]!
}


  1. Sample query to send array of objects:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
mutation {
  createObjects(objects: {
    objects: [
      { id: "1", name: "Object 1" },
      { id: "2", name: "Object 2" },
      { id: "3", name: "Object 3" }
    ]
  }) {
    id
    name
  }
}


  1. Handle the array of objects in the resolver of the mutation:
1
2
3
4
5
6
7
8
9
Mutation: {
  createObjects: (_, { objects }) => {
    // Loop through the array of objects and create new objects in the database
    return objects.map(object => {
      // Create object in the database and return it
      return createObject(object);
    });
  }
}


By following these steps, you can send an array of objects with a GraphQL mutation and process them in your server-side application.