Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL object property should be a list of strings

How do I make a schema for an object property that is an array of strings in GraphQL? I want the response to look like this:

{
  name: "colors",
  keys: ["red", "blue"]
}

Here is my Schema

var keysType = new graphql.GraphQLObjectType({
  name: 'keys',
  fields: function() {
    key: { type: graphql.GraphQLString }
  }
});

var ColorType = new graphql.GraphQLObjectType({
  name: 'colors',
  fields: function() {
    return {
      name: { type: graphql.GraphQLString },
      keys: { type: new graphql.GraphQLList(keysType)
    };
  }
});

When I run this query I get an error and no data, the error is just [{}]

query { colors { name, keys } }

However when I run a query to return just the name I get a successful response.

query { colors { name } }

How do I create a schema that returns an array of strings for when I query for keys?

like image 818
Mdd Avatar asked Jun 23 '16 15:06

Mdd


People also ask

What is object type in GraphQL?

Character is a GraphQL Object Type, meaning it's a type with some fields. Most of the types in your schema will be object types. name and appearsIn are fields on the Character type. That means that name and appearsIn are the only fields that can appear in any part of a GraphQL query that operates on the Character type.

Is GraphQL ID a String?

ID is a scalar type described in the GraphQL specification (working draft October 2016): The ID type is serialized in the same way as a String; however, it is not intended to be human‐readable. While it is often numeric, it should always serialize as a String.


1 Answers

I figured out the answer. The key is to pass the graphql.GraphQLString into graphql.GraphQLList()

The schema becomes:

var ColorType = new graphql.GraphQLObjectType({
  name: 'colors',
  fields: function() {
    return {
      name: { type: graphql.GraphQLString },
      keys: { type: new graphql.GraphQLList(graphql.GraphQLString)
    };
  }
});

Using this query:

query { colors { name, keys } }

I get the desired results:

{
  name: "colors",
  keys: ["red", "blue"]
}
like image 140
Mdd Avatar answered Oct 06 '22 22:10

Mdd