2016-08-24 44 views
6

在服務器啓動(node index.js)我收到以下錯誤與我GraphQL的NodeJS服務器:GraphQL參數數量錯誤:參數類型必須是輸入類型,但有:函數GraphQLObjectType(配置){

Error: Query.payment(data:) argument type must be Input Type but got: function GraphQLObjectType(config) { _classCallCheck(this, GraphQLObjectType);

此錯誤發生當我改變了我原來的ARGS從字符串

 args: { 
      data: { type: graphQL.GraphQLString } 
     }, 

要的對象類型:

 args: { 
      data: { type: graphQL.GraphQLObjectType } 
     }, 

我需要一個對象類型,因爲我需要發送幾個字段作爲參數。

GraphQL服務器:

var Query = new graphQL.GraphQLObjectType({ 
    name: 'Query', 
    fields: { 
     payment: { 
      type: graphQL.GraphQLString, 
      args: { 
       data: { type: graphQL.GraphQLObjectType } 
      }, 
      resolve: function (_, args) { 
       // There will be more data here, 
       // but ultimately I want to return a string 
       return 'success!'; 
      } 
     } 
    } 
}); 

我怎麼能允許它接受一個對象?


前端(如果需要的話,但在錯誤發生的事情我甚至派在此之前。):

var userQuery = encodeURIComponent('{ payment (data: { user : "test" })}'); 

$.get('http://localhost:4000/graphql?query=' + userQuery, function (res) { 
     //stuff 
}); 

回答

12

如果你想使用對象作爲參數,你應該使用GraphQLInputObjectType而不是GraphQLObjectType。請記住,GraphQL是基於強類型的,因此不允許使用通用GraphQLObjectType作爲arg類型,然後動態查詢args。你必須明確地定義這個輸入對象的所有可能的領域(並選擇其中哪些是必需的,哪些不是)

嘗試使用這種方法:

// your arg input object 
var inputType = new GraphQLInputObjectType({ 
    name: 'paymentInput', 
    fields: { 
     user: { 
      type: new GraphQLNonNull(GraphQLString) 
     }, 
     order: { 
      type: GraphQLString 
     }, 
     ...another fields 
    } 
}); 

var Query = new graphQL.GraphQLObjectType({ 
    name: 'Query', 
    fields: { 
     payment: { 
      type: graphQL.GraphQLString, 
      args: { 
       data: { type: new GraphQLNonNull(inputType) } 
      }, 
      resolve: function (_, args) { 
       // There will be more data here, 
       // but ultimately I want to return a string 
       return 'success!'; 
      } 
     } 
    } 
}); 
+0

感謝主戴夫。我最終將其改爲「突變」並指定了字段。順便說一句,有兩個問題:'1)'有沒有更好的方法來寫我的POST查詢比'encodeURIComponent('{payment(data:{user:「test」})}');'?如果對象很大,手動指定每個字段會變得笨拙。 '2)'GraphQL似乎需要一個'Query',儘管我只需要一個'Mutation'。我是否需要隨時查詢或在某處是否有選項? – Growler

+0

'1)'我推測你正在使用jQuery ajax根據你給定的例子來調用graphql。不幸的是,我無法幫助你,因爲在我的項目中,我正在'ReactJS'前端使用'Relay',它負責這個。 '2)'顯然,在模式中總是需要'Query'。看看'graphql-js'源代碼[https://github.com/graphql/graphql-js/blob/master/src/type/schema.js#L58] 我希望我已經至少幫助了一些東西 – LordDave

相關問題