2017-08-30 76 views
1

可能標題不適合我的問題,但讓我解釋我的情況。 我與Graphql schema.Here工作是我最初的schema.js文件https://github.com/sany2k8/graphql-udemy/blob/master/schema/schema.jsGraphql需要模塊外部vs內部GraphQLObjectType

和它工作得很好,那麼我決定把它分割成不同的小文件,例如root_query_type.jsmutation.jsuser_type.jscompany_type.js。所有文件都作爲模塊導出並循環使用。例如 -

user_type.js

const graphql = require('graphql'); 
const axios = require('axios'); 
const { GraphQLObjectType, GraphQLString, GraphQLInt } = graphql; 
//const CompanyType = require('./company_type'); // *this line causing error* 


const UserType = new GraphQLObjectType({ 
    name: "User", 
    fields:() => ({ 
     id:{ type: GraphQLString}, 
     firstName:{ type: GraphQLString}, 
     age:{ type: GraphQLInt}, 
     company :{ 
      type: require('./company_type'), // *this line fix the error* 
      resolve(parentValue, args){ 
       return axios.get(`http://localhost:3000/companies/${parentValue.companyId}`) 
        .then(res => res.data) 
      } 
     } 
    }) 
}); 

module.exports = UserType; 

company_type.js

const graphql = require('graphql'); 
const axios = require('axios'); 
const { GraphQLObjectType, GraphQLString, GraphQLList } = graphql; 
const UserType = require('./user_type'); 


const CompanyType = new GraphQLObjectType({ 
    name: "Company", 
    fields:()=> ({ 
     id: { type: GraphQLString}, 
     name: { type: GraphQLString}, 
     description: { type: GraphQLString}, 
     users:{ 
      type: new GraphQLList(UserType), 
      resolve(parentValue, args){ 
       return axios.get(`http://localhost:3000/companies/${parentValue.id}/users`) 
        .then(res => res.data) 
      } 
     } 
    }) 
}); 

module.exports = CompanyType; 

在我user_type.js文件,當我使用const CompanyType = require('./company_type');在文件中這樣的頂const UserType它向我顯示以下錯誤消息

Error: User.company field type must be Output Type but got: [object Object].

但是如果我註釋掉那條線並直接放它然後它就會起作用。

company :{ 
       type: require('./company_type'), 
       resolve(parentValue, args){ 
        return axios.get(`http://localhost:3000/companies/${parentValue.companyId}`) 
         .then(res => res.data) 
       } 
      } 

所以基本上我的問題是,爲什麼它不與const CompanyType = require('./company_type');工作,但type: require('./company_type')工作。我可能是一個簡單的邏輯問題,但它無法找到。請幫助我。

回答

3

您看到的行爲並不是特定於GraphQL,而是一般的節點。您的模塊中存在循環依賴關係,這會導致user_type.js中的require語句解析爲company_type.js的不完整副本。

According to the docs,給出了兩個模塊(a.jsb.js)需要對方:

When main.js loads a.js , then a.js in turn loads b.js . At that point, b.js tries to load a.js . In order to prevent an infinite loop, an unfinished copy of the a.js exports object is returned to the b.js module. b.js then finishes loading, and its exports object is provided to the a.js module.

移動需要你的語句定義的出口裏面是一個解決方案。您還可以將您的導出定義以上您需要調用以獲得相同的影響。 This question更深入地研究了循環依賴關係,並提供了一些替代解決方案。作爲一個側面說明,這是我建議遠離以編程方式聲明GraphQL架構的原因之一。您可以使用graphql-toolsgenerate-schema從GraphQL語言文檔生成模式。這可以防止您與潛在的循環依賴關係打交道,併產生更具可讀性的模式。您也可以輕鬆地模塊化您的模式;你的類型定義只是字符串,你的解析器只是對象 - 兩者都可以很容易地組合。

+0

是的,我現在明白了。感謝您的鏈接參考。 –