2017-04-14 120 views
1

因此,我嘗試做的事情是使用GraphQL從數據庫(在我的情況下是MongoDB)中檢索過濾的數據。如何使用過濾器定義和執行GraphQL查詢

在「MySQL語言」中講述如何在GraphQL中實現where子句?

我遵循這個教程: 與濾波器https://learngraphql.com/basics/using-a-real-data-source/5

查詢被這樣定義:

const Query = new GraphQLObjectType({ 
    name: "Queries", 
    fields: { 
    authors: { 
     type: new GraphQLList(Author), 
     resolve: function(rootValue, args, info) { 
     let fields = {}; 
     let fieldASTs = info.fieldASTs; 
     fieldASTs[0].selectionSet.selections.map(function(selection) { 
      fields[selection.name.value] = 1; 
     }); 
     return db.authors.find({}, fields).toArray(); 
     } 
    } 
    } 
}); 

這裏棘手的部分是在resolve功能的info參數。幾點說明我已經在這裏找到:http://pcarion.com/2015/09/26/graphql-resolve/

所以這是AST(抽象語法樹)

任何人都可以請提供一些基本的現實生活中的例子代碼,將展示如何定義執行的以下查詢: 獲取所有作者的名字==約翰

謝謝!

回答

2

有沒有必要檢查AST。這將非常費力。

您只需要在author字段中定義一個參數。這是解析器的第二個參數,因此您可以檢查該爭論並將其包含在Mongo查詢中。

const Query = new GraphQLObjectType({ 
    name: "Queries", 
    fields: { 
    authors: { 
     type: new GraphQLList(Author), 

     // define the arguments and their types here 
     args: { 
     name: { type: GraphQLString } 
     }, 

     resolve: function(rootValue, args, info) { 
     let fields = {}; 
     // and now you can check what the arguments' values are 
     if (args.name) { 
      fields.name = args.name 
     } 
     // and use it when constructing the query 
     return db.authors.find(fields, fields).toArray(); 
     } 
    } 
    } 
}); 
+2

作爲一個小概覽什麼其他過濾器/參數是可能的,這裏是一個文章中,我們如何使用參數在Graphcool來實現過濾器:https://www.graph.cool/docs/tutorials/designing-powerful-apis -with-graphql查詢參數,aing7uech3 – marktani

相關問題