【问题标题】:graphql: sort by nested fieldgraphql:按嵌套字段排序
【发布时间】:2018-09-13 11:27:01
【问题描述】:

假设我有 2 张桌子:
- 用户(ID、姓名、帖子)
- 帖子(id、消息、用户)

如何按用户名(desc)获取前 10 个帖子顺序?

我的架构如下所示:

var PostType = new GraphQLObjectType({
  name: "Post",
  fields: () => ({
    id: { type: GraphQLInt },
    message: { type: GraphQLString },
    user: {
      type: UserType,
      args: {
        orderBy: { type: sortType }
      },
      resolve(parent, args) {
        console.info("Post resolve called.");
        return userMap[parent.user];
      }
    }
  })
});

var RootQuery = new GraphQLObjectType({
  name: "RootQueryType",
  fields: {
    allPosts: {
      type: new GraphQLList(PostType),
      resolve(parentValue, args) {
        console.info("allPosts resolve called.");
        return postData;
      }
    }
  }
});

和查询:

{
  allPosts {
    message
    user (orderBy: {field: "name", direction: ASC}) {
      name
    }
  }
}

有什么办法,我可以在 allPosts 解析器函数之前调用用户解析器函数吗?因为,我试图获取按名称排序的 10 个用户,然后将帖子 ID 传递给 allPosts 解析器。

【问题讨论】:

    标签: graphql


    【解决方案1】:

    GraphQL 字段以自上而下的方式解析。这意味着首先解析allPosts,然后解析messageuser 字段(同时),然后解析name 字段。这必须发生,因为“父”或根字段的已解析值决定了该值,然后将其作为根值传递给其子字段的解析器。信息从“高级”解析器流向“低级”解析器,而不是相反。

    您的orderBy 参数可能应该是allPosts 字段上的参数,而不是user 字段。这样做有两个原因:(1) 从概念上讲,无论排序标准如何,您都在对 allPosts 返回的帖子进行排序——按照惯例,将排序放在那里是有意义的; (2) allPosts 解析器需要的参数可能比user 解析器需要的多。

    要使上述工作正常进行,您可能需要修改识别排序标准的方式(例如,将field 设置为类似user.name 的路径)。您可能还需要“提升”将用户填充到 allPosts 解析器的逻辑。例如:

    resolve(parentValue, { sortBy: { path, direction } }) {
      const data = postData.map(post => {
        post.user = userMap[post.user]
        return post
      });
      // using lodash
      return orderBy(data, [(post) => get(post, path)], [direction])
    }
    

    可以通过解析作为解析器函数的第四个参数传入的info 对象来确定请求中其他字段(包括参数)的选择集。不过这很痛苦,我不知道这种特殊情况是否真的证明这样做是合理的。您可以在this answer 中阅读有关该方法的更多信息。

    【讨论】:

    • 我认为我无法做到这一点。谢谢。!!
    猜你喜欢
    • 1970-01-01
    • 2018-10-22
    • 2019-10-25
    • 2021-08-07
    • 2017-01-28
    • 2015-10-24
    • 2020-09-18
    • 2015-11-22
    • 2017-12-31
    相关资源
    最近更新 更多