2016-08-13 50 views
0

我试图使用“列表”实现窗口分页。我不需要基于光标的连接解决方​​案,因为我需要向用户显示带编号的页面。GraphQL:实现定期列表的窗口分页

有“用户”和“发布”对象。“用户”与“发布”具有一对多关系。

使用graphql-JS的架构, 这里是我的用户类型和postType模式:

var userType = new GraphQLObjectType({ 
    name: 'User', 
    fields:() => ({ 
     id: globalIdField('User'), 
     posts: { 
      type: new GraphQLList(postType), 
      args: { 
       page:{ 
        type: GraphQLInt, 
        defaultValue: 0 
       } 
      }, 
      resolve: (_, args) => { 
       //code to return relevant result set 
      }, 
     }, 
     totalPosts:{ 
      type: GraphQLInt, 
      resolve:() => { 
       //code to return total count 
      } 
     }, 
    }), 
    interfaces: [nodeInterface], 
}); 


var postType = new GraphQLObjectType({ 
    name: 'Post', 
    fields:() => ({ 
     id: globalIdField('Post'), 
     name: {type: GraphQLString}, 
     //other fields 
    }), 
    interfaces: [nodeInterface], 
}); 

请注意在 “用户类型” 中的 “totalPosts” 字段。既然会有其他的用户列表,需要相同的分页,我最终会在分段中保留大量的“全部{Type}”变量。如果我能以某种方式发送List结果中的totalCount,这可以解决。

https://github.com/facebook/graphql/issues/4此问题讨论如何在列表上实现一个包装,以将totalCount包含在结果集中。

我试图创建一个像这样的包装:

var postList = new GraphQLObjectType({ 
    name: 'PostList', 
    fields:()=>({ 
     count: { 
      type: GraphQLInt, 
      resolve:()=>getPosts().length //this is total count 
     }, 
     edges: { 
      type: new GraphQLList(postType), 
      resolve:() => { 
       return getPosts() ; // this is results for the page, though I don't know how to use 'page' argument here 
      }, 
     } 

    }), 
    interfaces: [nodeInterface], 
}); 

,但我应该怎么这个连接userTypeposts场?我怎么能在这个包装上使用'页面'参数,就像我在原始的userType中一样?

回答

1

我应该如何将它连接到userType的posts字段?我怎么能在这个包装上使用'页面'参数,就像我在原始的userType中一样?

实现你试图做一个简单的方法是定义一个包装类型postList这样的:

var postList = new GraphQLObjectType({ 
    name: 'PostList', 
    fields:()=>({ 
     count: { type: GraphQLInt }, 
     edges: { type: new GraphQLList(postType) } 
     // Consider renaming 'edges'. In your case, it's a list, not a 
     // connection. So, it can cause confusion in the long run. 
    }), 
}); 

然后在userType定义,添加包装的领域键入并定义它的解析函数,如下所示。至于参数page,只需在定义字段类型posts时进行描述。

posts: { 
    type: postList, 
    args: { 
     page:{ 
      type: GraphQLInt, 
      defaultValue: 0 
     }, 
     ...otherArgs 
    }, 
    resolve: async (_, {page, ...otherArgs}) => { 
     // Get posts for the given page number. 
     const posts = await db.getPosts(page); 

     // Prepare a server-side object, which corresponds to GraphQL 
     // object type postList. 
     const postListObj = { 
      count: posts.length, 
      edges: posts 
     }; 
     // Consider renaming 'edges'. In your case, it's a list, not a 
     // connection. So, it can cause confusion in the long run. 
    }, 
}, 
+0

谢谢!有效。不得不删除接口:[nodeInterface],从postList包装 – sanandrl

+0

我很高兴你发现它很有用。根据您的反馈,我从'postList'包装中删除'interfaces'字段。谢谢! –