【问题标题】:Unable to reference GraphQLObjectType while creating it创建时无法引用 GraphQLObjectType
【发布时间】:2016-07-14 23:20:18
【问题描述】:

我正在尝试从 json 配置动态生成 graphql 方案。但我无法为自己创建一个 GraphQLList。

json:

{
  "label": "user",
  "properties": [
    {
      "key": "name",
      "type": "string"
    },
    {
      "key": "id",
      "type": "id"
    },
    {
      "key": "birthday",
      "type": "date"
    },
    {
      "key": "gender",
      "type": "string"
    },
    {
      key: 'friends',
      type: 'string'
    }
  ]
}

javascript代码生成:

graphSchemes.forEach(function (graphScheme) {
 graphQLObjects[graphScheme.label] = new graphql.GraphQLObjectType({
  name: graphScheme.label,
  fields: graphScheme.properties.reduce((fields, property) => {
    if (property.key === 'friends') {
      fields[property.key] = {
        type: new graphql.GraphQLList(graphQLObjects[graphScheme.label])
      };
      return fields;
    }
    fields[property.key] = {
      type: TYPES[property.type]
    };
    return fields;
  }, {})
});

});

这里的问题是:

type: new graphql.GraphQLList(graphQLObjects[graphScheme.label])

没有“graphQLObjects[graphScheme.label]”

我该如何解决这个问题?有什么建议?

【问题讨论】:

    标签: javascript graphql


    【解决方案1】:

    通过将字段放入包装函数中,字段可以引用类型本身。

    一个例子:

    var routeType = new GraphQLObjectType({
      name: 'MessageRoute',
      fields: function () {
        return {
          name: {
            type: GraphQLString
          },
          routes: {
            type: new GraphQLList(routeType),
            resolve: (route) => {
              return route.routes;
            }
          }
        };
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2017-06-22
      • 1970-01-01
      • 2019-03-13
      • 2019-05-20
      • 2022-10-12
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      相关资源
      最近更新 更多