将过滤选项添加到GraphQl分页查询中



我在我的一个项目中使用了这个不错的apollo umerversal-starter-kit。我有一项任务是在此页面中添加过滤选项,以过滤具有超过2个注释的帖子。

入门套件使用Apollo GraphQl-Server作为后端。这些帖子的架构描述看起来像这样:

# Post
type Post {
  id: Int!
  title: String!
  content: String!
  comments: [Comment]
}
# Comment
type Comment {
  id: Int!
  content: String!
}
# Edges for PostsQuery
type PostEdges {
  node: Post
  cursor: Int
}
# PageInfo for PostsQuery
type PostPageInfo {
  endCursor: Int
  hasNextPage: Boolean
}
# Posts relay-style pagination query
type PostsQuery {
  totalCount: Int
  edges: [PostEdges]
  pageInfo: PostPageInfo
}
extend type Query {
  # Posts pagination query
  postsQuery(limit: Int, after: Int): PostsQuery
  # Post
  post(id: Int!): Post
}

postsQuery用于生成帖子的分页结果

这是postsQuery解决方案的方式(在此处完成代码(

async postsQuery(obj, { limit, after }, context) {
      let edgesArray = [];
      let posts = await context.Post.getPostsPagination(limit, after);
      posts.map(post => {
        edgesArray.push({
          cursor: post.id,
          node: {
            id: post.id,
            title: post.title,
            content: post.content,
          }
        });
      });
      let endCursor = edgesArray.length > 0 ? edgesArray[edgesArray.length - 1].cursor : 0;
      let values = await Promise.all([context.Post.getTotal(), context.Post.getNextPageFlag(endCursor)]);
      return {
        totalCount: values[0].count,
        edges: edgesArray,
        pageInfo: {
          endCursor: endCursor,
          hasNextPage: values[1].count > 0
        }
      };
    }

和,这是一个GraphQl查询,在前端使用React post_list组件(组件的完整代码在此处(

(
query getPosts($limit: Int!, $after: ID) {
    postsQuery(limit: $limit, after: $after) {
        totalCount
        edges {
            cursor
            node {
                ... PostInfo
            }
        }
        pageInfo {
            endCursor
            hasNextPage
        }
    }
}

这是一个很长的介绍:-),对不起

问题:

如何将过滤选项添加到post_list组件/页面?我有点理解问题的反应,但我不了解GraphQl。我应该向postsQuery(limit: $limit, after: $after)添加一个新变量,以便看起来像postsQuery(limit: $limit, after: $after, numberOfComments: $numberOfComments)吗?然后以某种方式在后端解决它?或者,我走错了轨道,应该朝着不同的方向思考吗?如果是这样,您能指出我的方向正确吗?: - (

预先感谢您!

imo我一定会在后端解决这个问题。至于是否应该是一个新变量,我个人会说是的,您的帖子可以更新以支持评论计数的过滤,理想情况下,您希望作为DB请求的一部分,以便您知道自己知道自己是获取您想要的帖子类型的数量,否则它将打开分页中的edgecase的门。

另一个选项是针对策展柱或过滤插座的新查询,或者您想调用的任何已知已经根据注释数量过滤的任何问题。

最新更新