【问题标题】:Add filtering option to the graphql paginated query向 graphql 分页查询添加过滤选项
【发布时间】:2017-12-01 22:20:53
【问题描述】:

我在我的一个项目中使用了这个不错的apollo-universal-starter-kit。我的任务是向this page 添加过滤选项,以过滤超过 2 个 cmets 的帖子。

入门套件使用 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 的解析方式如下(完整代码here

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 组件一起使用(该组件的完整代码是 here

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

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

问题:

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

提前谢谢你!

【问题讨论】:

    标签: reactjs graphql apollo react-apollo apollo-client


    【解决方案1】:

    IMO 我肯定会在后端解决这个问题。至于它是否应该是一个新变量,我个人会说是的,并且您的 Post.getPostsPagination 可以更新以支持对评论计数的过滤,理想情况下您希望将其作为数据库请求的一部分,以便您知道自己是获取您想要的 N 种类型的帖子,否则它将为您的分页中的边缘案例打开大门。

    另一个选项是对 CuratedPosts 或 FilteredPosts 的新查询,或者您想要调用的任何已经知道根据 cmets 数量进行过滤的查询。

    【讨论】:

      猜你喜欢
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      • 2018-08-29
      • 2019-12-29
      • 2019-01-21
      • 1970-01-01
      • 2018-11-14
      • 1970-01-01
      相关资源
      最近更新 更多