【问题标题】:In GraphQL, how can I specify nested arrays as a field type?在 GraphQL 中,如何将嵌套数组指定为字段类型?
【发布时间】:2016-03-04 11:43:15
【问题描述】:

在 GraphQL 中,我正在尝试创建 GeoJSON 对象类型。

当我指定一个GraphQLFloats 的 4 维数组时,我在启动服务器时收到错误:

Error: Decorated type deeper than introspection query.

类型定义如下所示:

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,
    }
  }
});

如何解决此错误?这是它在源代码中抛出的地方:

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

【问题讨论】:

    标签: graphql-js


    【解决方案1】:

    我们最终定义了GeoJSON 标量类型而不是对象类型。这将允许我们对 GeoJSON 规范执行严格的验证。现在,为了让我们继续前进,我们定义了一个(完全未实现的)自定义 GeoJSON 类型:

    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;
        }
    });
    

    ... 这允许我们像这样使用它:

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

    您可以使用此策略定义自定义类型来表示数组数组,或定义自定义类型以仅表示嵌套数组,然后使用new GraphQLList(CoordinatesType) 等。这取决于您正在建模的数据.

    【讨论】:

      猜你喜欢
      • 2019-05-30
      • 2018-08-15
      • 2022-01-03
      • 2019-12-14
      • 2019-07-07
      • 2017-12-18
      • 2022-01-20
      • 2013-03-24
      • 2019-06-24
      相关资源
      最近更新 更多