Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In GraphQL, how can I specify nested arrays as a field type?

Tags:

graphql-js

In GraphQL, I'm trying to create a GeoJSON object type.

When I specify a 4-dimensional array of GraphQLFloats, I get an error when I start my server:

Error: Decorated type deeper than introspection query.

The type definition looks like this:

var GraphQLGeoJSON = new GraphQLObjectType({
  name: 'GeoJSON',
  fields: {
    type: {
      type: GraphQLString,
      resolve: (obj) => obj.type,
    },
    coordinates: {
      type: new GraphQLList(new GraphQLList(new GraphQLList(new GraphQLList(GraphQLFloat)))),
      resolve: (obj) => obj.coordinates,
    }
  }
});

How can I resolve this error? This is where it's thrown in the source:

https://github.com/graphql/graphql-js/blob/568dc52a4f9cc9bdec4f9283e6e528970af06cde/src/utilities/buildClientSchema.js#L105

like image 803
colllin Avatar asked Nov 30 '15 18:11

colllin


1 Answers

We ended up defining a GeoJSON scalar type instead of an object type. This would allow us to perform strict validations against the GeoJSON spec. For now, just to keep us moving, we've defined a (completely unimplemented) custom GeoJSON type:

var GeoJSON = new GraphQLScalarType({
    name: 'GeoJSON',
    serialize: (value) => {
        // console.log('serialize value', value);
        return value;
    },
    parseValue: (value) => {
        // console.log('parseValue value', value);
        return value;
    },
    parseLiteral: (ast) => {
        // console.log('parseLiteral ast', ast);
        return ast.value;
    }
});

... which allows us to use it like this:

var Geometry = new GraphQLObjectType({
    name: 'Geometry',
    fields: () => ({
        id: globalIdField('Geometry'),
        geojson: {
            type: GeoJSON,
        },
    },
};

You could use this strategy to define a custom type to represent an array of arrays, or define a custom type to represent just the nested arrays, and then use new GraphQLList(CoordinatesType), etc. It depends on the data you're modeling.

like image 111
colllin Avatar answered Sep 30 '22 18:09

colllin