【问题标题】:How to implement pagination in graphql which returns pagination metadata along with dataset如何在graphql中实现分页,它返回分页元数据和数据集
【发布时间】:2020-08-15 19:17:41
【问题描述】:

目前我使用 graphql 默认分页,即使用限制偏移量(代码如下)。这工作正常。但是我们如何包含分页元数据而不是团队列表。并连同此一起返回分页元数据。我使用 sequalize 来获取数据

            type Query {
            allTeams(page:Int, pageSize:Int): [Team]
        }
        type Team {
            id: Int
            name: String  
        }

        //resolver with pagination   

        const paginate = ( page, pageSize ) => { 
          var offset = page * pageSize;
          var limit =  pageSize;  
          return {
            offset,
            limit,
          };
        };

        export const resolvers = {
            Query: {     
                  allTeams: async (obj, args, context, info ) =>  Teams.findAll(           
                  paginate( args.page, args.pageSize ),         
                ),
            },
        }

上面的代码只会返回团队列表。 有什么方法可以返回包含团队列表和分页详细信息的输出

         {
          "data": {
            "allTeams": [
              {
                "id": 4,
                "name": "Team created from postman",

              },
              {
                "id": 5,
                "name": "Team created from postman",

              }
              ]
            },
               "pageInfo": {
                "currentPage": 2,
                "perPage": 2,
                "itemCount": 4,
                "pageCount": 2,
                "hasPreviousPage": true,
                "hasNextPage": false
              }
        }

【问题讨论】:

    标签: node.js pagination graphql sequelize.js apollo


    【解决方案1】:

    是的,您只需将分页元数据添加到架构中并在解析器中提供数据。因此,对于您希望实现的输出,架构如下所示:

    type Query {
      teams(page:Int, pageSize:Int): TeamsConnection
    }
    
    type TeamsConnection {
      results: [Team]
      pageInfo: PageInfo
    }
    
    type Team {
      id: Int
      name: String  
    }
    
    type PageInfo {
      currentPage: Int
      perPage: Int
      itemCount: Int
      pageCount: Int
      hasPreviousPage: Boolean
      hasNextPage: Boolean
    }
    
    

    然后,您的解析器将需要返回响应数据的新形状。所以像:

    export const resolvers = {
      Query: {     
        allTeams: async (obj, args, context, info ) => {
          const results = awaitTeams.findAll(           
            paginate(args.page, args.pageSize),         
          );
          return {
            results,
            pageInfo: {...}
          }
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-26
      • 2017-11-18
      • 2014-03-13
      • 1970-01-01
      • 2016-12-28
      • 1970-01-01
      • 2020-02-02
      • 2010-09-19
      • 1970-01-01
      相关资源
      最近更新 更多