相关的Graphql对象给出undefined

时间:2018-06-03 17:43:36

标签: node.js sequelize.js graphql

启动服务器时出现此错误

  

错误:预期未定义为GraphQL类型。

更新:我认为这与javascript需要彼此有关。解决这个问题的最佳方法是什么?

我在文件accountTypes.js中有一个帐户类型

const { channelType } = require('../channel/channelTypes');

//Define Order type
const accountType = new GraphQLObjectType({
  name: 'Account',
  description: 'An account',
  fields: () => ({
    id: {
      type: new GraphQLNonNull(GraphQLInt),
      description: 'The id of the account.'
    },
    name: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'Name of the account.'
    },
    channel: {
      type: channelType,
      resolve: resolver(db.Account.Channel),
      description: 'Channel'
    },
    etc...

我的频道类型是在channelTypes.js

const { accountType } = require('../account/accountTypes');

// Define Channel type
const channelType = new GraphQLObjectType({
  name: 'Channel',
  description: 'A Channel',
  fields: () => ({
    id: {
      type: new GraphQLNonNull(GraphQLInt),
      description: 'ID of the channel.'
    },
    name: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'Name of the channel',
      deprecationReason: 'We split up the name into two'
    },
    accounts: {
      type: new GraphQLList(accountType),
      description: 'accounts associated with this channel',
      resolve: resolver(db.Channel.Account)
    }
  })
});

有问题的代码在我的channelTypes.js文件中。由于某种原因,accountType因未定义而过来。我使用module.exports导出相应文件中的accountType和channelType。当我在通道文件中注释掉accountType代码时,该帐户工作正常。我正在尝试从帐户或与渠道相关联的所有帐户中获取渠道,但目前只有来自帐户端的渠道才有效。

1 个答案:

答案 0 :(得分:1)

我回答了一个非常相似的问题here,但我认为它们有点不同。我尝试在那里解释一下模块系统,但基本上答案是在处理递归类型时只需将函数中某个类型的fields属性包装起来。

编辑:也不要对模块对象进行解构。当您具有循环依赖关系时,循环相关模块将获得对模块的引用,但不会进行初始化。然后,当您对它们进行解构时,变量将获得undefined,因为模块还没有属性。

const accountTypes = require('../account/accountTypes');

// Define Channel type
const channelType = new GraphQLObjectType({
  name: 'Channel',
  description: 'A Channel',
  fields: () => ({
    id: {
      type: new GraphQLNonNull(GraphQLInt),
      description: 'ID of the channel.'
    },
    name: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'Name of the channel',
      deprecationReason: 'We split up the name into two'
    },
    accounts: {
      type: new GraphQLList(accountTypes.accountType),
      description: 'accounts associated with this channel',
      resolve: resolver(db.Channel.Account)
    }
  })
});