Joel Biffin
Joel Biffin

Reputation: 378

Retrieve array of Objects in GraphQL without defining array type

I am using GraphQL to return necessary JSON objects.

I have a defined type called Colour in my server and it is used in multiple different queries. There is one instance where instead of just returning one Colour type by a query such as

query Colour($id: Int!) {
  colour(id: $id) {
    hue
    saturation
    luminosity
    red
    green
    blue
  }
}

I need to return an array of Colour without having to create a new type called Colours on the backend.

I'd need the response to resemble

{
  "data": {
    "colours": [
      { "hue": 0, "saturation": 100, "luminosity": 100, "red": 255, "green": 0, "blue": 0 },
      { "hue": 0, "saturation": 0, "luminosity": 100, "red": 255, "green": 255, "blue": 255 }
    ]
  }
}

Is there a way I could run one single query over an array of ids to get an object with this shape?

Upvotes: 1

Views: 585

Answers (1)

Ken Chan
Ken Chan

Reputation: 90427

You don't need to create another new type called Colours for a list of Colour. Just use [Colour] to represent a list. Also , you have to define another root query field for it :

type Query {
    colours(ids:[Int]) : [Colour]
}

Unfortunately, if you are looking for a way that will return a list of colours with your desired structure by inputting a list of ID without any code changes , I don't think it is possible .

Upvotes: 3

Related Questions