首页 > 解决方案 > 相关的 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 代码时,该帐户可以正常工作。我试图能够从帐户或与频道关联的所有帐户获取频道,但目前只有来自帐户端的频道有效。

标签: node.jssequelize.jsgraphql

解决方案


我在这里回答了一个非常相似的问题,但我认为它们有点不同。我试图在那里解释一下模块系统,但基本上答案是,在处理递归类型时,只需将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)
    }
  })
});

推荐阅读