创建它时无法引用GraphQLObjectType

时间:2016-03-27 16:30:44

标签: javascript graphql

我正在尝试从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]”

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

1 个答案:

答案 0 :(得分:0)

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

一个例子:

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