How to query list of objects with array as an argument in GraphQL

GraphqlGraphql Js

Graphql Problem Overview


I'm trying to query a list of objects having array of IDs. Something similar to following SQL query:

SELECT name FROM events WHERE id IN(1,2,3,...);

How do I achieve this in GraphQL?

Graphql Solutions


Solution 1 - Graphql

You can definitely query with an array of values! Here's what the query itself would look like:

{
  events(containsId: [1,2,3]) {
    ...
  }
}

And the type would look something like:

const eventsType = new GraphQLObjectType({
  name: 'events',
  type: // your type definition for events,
  args: {
    containsId: new GraphQLList(GraphQLID)
  },
  ...
});

If you wanted to parameterize this query, here's an example of that:

{
  query: `
    query events ($containsId: [Int]) {
      events(containsId: $containsId) {
        id
        name
      }
    }
  `,
  variables: {
    containsId: [1,2,3]
  }
}

Solution 2 - Graphql

In my use case I did as:

query:

vehicleTypes: { name: ["Small", "Minivan"] }

input:

vehicleTypes: VehicleTypesInput

then use like this:

Input VehicleTypesInput {
    name: [String]!
}

Solution 3 - Graphql

I just do this:

query nameOfYourQuery {
  allEvents(filter: { id: { in: [1,2,3] } }) {
    nodes {
      name
    }
  }
}

If the array is a variable, then it would look like this (in Gatsby, at least):

query nameOfYourQuery($arrayOfID: [String]) {
  allEvents(filter: { id: { in: $arrayOfID: [String] } }) {
    nodes {
      name
    }
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRafael SedrakyanView Question on Stackoverflow
Solution 1 - GraphqlbrowserlessView Answer on Stackoverflow
Solution 2 - GraphqlGabriel Borges OliveiraView Answer on Stackoverflow
Solution 3 - GraphqlFélix ParadisView Answer on Stackoverflow