【问题标题】:Each Node of data perform separate database request每个数据节点执行单独的数据库请求
【发布时间】:2017-06-30 10:36:00
【问题描述】:

以下是 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 },

我的服务器与我的文档一样发送多个请求,这里它将发送 5 个不同的请求。

如何优化这些请求在一个请求中获取所有数据

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

【问题讨论】:

  • 您的意思是要使用一个请求返回多个对象,例如user?每个user 都会有上面指定的id 之一?
  • 是的,我想获取[] 中的所有用户并执行一个请求,并尽可能减少数据库请求

标签: graphql graphql-js


【解决方案1】:

在这种情况下,您可以创建一个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']
}

【讨论】:

    【解决方案2】:

    这是 Dataloader 的工作,这是 Facebook 的一个库,专门用于将这样的查询批处理在一起:

    https://github.com/facebook/dataloader

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      • 2010-10-27
      • 2023-04-03
      相关资源
      最近更新 更多