2017-02-12 48 views
0

下面是GraphQLObject字段數據的每個節點執行單獨的數據庫請求

userId: { 
     type: GraphQLID, 
     resolve: obj => { 
      console.log(obj._id); 
      return obj._id; 
     } 
    }, 
    email: { type: GraphQLString }, 
    password: { type: GraphQLString }, 
    firstName: { type: GraphQLString }, 
    lastName: { type: GraphQLString }, 

礦服務器sents多個同樣請求作爲礦的文件,在這裏其將發送5個不同的請求。

如何優化這些請求得到的所有數據在一個請求

589800cf39b58b29c4de90dd 
-------------------------------- 
    58980673e7c9a733009091d1 
-------------------------------- 
    58985339651c4a266848be42 
-------------------------------- 
    589aac5f884b062b979389bc 
-------------------------------- 
    589aad9d24989c2d50f2a25a 
+0

你的意思是你想使用一個請求返回像'user'這樣的許多對象嗎?並且每個'user'都有上面指定的'id'之一? – piotrbienias

+0

是的,我想在'[]'中獲得所有用戶並執行一個請求,並儘可能減少數據庫請求 –

回答

0

在這種情況下可以創建一個query方法,其將接受的array作爲參數,這將是ID的陣列中的這個案例。

getUsers: { 
    type: new GraphQLList(User), 
    args: { 
     ids: { 
      type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLID))) 
     } 
    }, 
    resolve: (root, args, context) => { 
     let query = 'SELECT * FROM users WHERE id = ANY($1)'; 

     return pgClient.query(query, [args.ids], (err, result) => { 
      // here you would access all returned rows in the result object 
      console.log(result); 
     }); 
    } 
} 

query變量會根據您使用的數據庫而有所不同。在這個例子中,我使用了PostgreSQL的node-postgres模塊。但是,這個概念是相同的 - 使用ID數組來執行返回所有用戶的單個查詢。

然後你可以調用該查詢:

query getUsers($ids: [ID!]!) { 
    getUsers(ids: $ids){ 
     id 
     email 
     ... 
    } 
} 

// and the variables below 
{ 
    ids: ['id#1', 'id#2', 'id#3'] 
}