Google App Engine 使用 nextPageToken 一次查询 50 个结果
Google App Engine query 50 results at a time with a nextPageToken
我的 GAE Cloud 端点中有以下 Api 方法:
@ApiMethod(name = "getConferences", path = "get_conferences", httpMethod = ApiMethod.HttpMethod.POST)
public List<Conference> getConferences(@Named("userId") Long userId) {
List<Conference> conferenceList = ofy().load().type(Conference.class)
.ancestor(Key.create(User.class, userId))
.order("-createdDate").list();
return conferenceList;
}
效果很好,return对我来说,给定用户创建的所有会议都按日期降序排列。 Conference
class 有以下 属性 指定它有一个 User
parent:
@Parent
private Key<User> userKey;
我的问题是,我怎样才能将上述方法更改为 return 一次只有 50 个结果(会议),并且还能够指定一个参数,该参数采用 nextPageToken 之类的东西来给我接下来的 50 个结果?
我在其他 API 方法中看到过这样做,但似乎无法找到适用于 GAE 或 Cloud Endpoints 的好示例。
- 而不是 returning
List<Conference>
你应该 return com.google.api.server.spi.response.CollectionResponse<Conference>
.
- 添加命名参数,例如
@Named("nextPageToken") String pageToken
。
- 如果
pageToken != null
,在.order()
之后你需要链接.startAt(Cursor.fromWebSafeString(pageToken))
- 您还需要添加
.limit(50)
,因为您希望它成为您的页面大小。
- 而不是
.list()
使用 .iterator()
,它有一个 getStartCursor()
方法。使用它和迭代器构造 CollectionResponse
.
有关如何使用游标的 non-Endpoints 示例,另请参阅 this page。其余的应该是微不足道的。
我的 GAE Cloud 端点中有以下 Api 方法:
@ApiMethod(name = "getConferences", path = "get_conferences", httpMethod = ApiMethod.HttpMethod.POST)
public List<Conference> getConferences(@Named("userId") Long userId) {
List<Conference> conferenceList = ofy().load().type(Conference.class)
.ancestor(Key.create(User.class, userId))
.order("-createdDate").list();
return conferenceList;
}
效果很好,return对我来说,给定用户创建的所有会议都按日期降序排列。 Conference
class 有以下 属性 指定它有一个 User
parent:
@Parent
private Key<User> userKey;
我的问题是,我怎样才能将上述方法更改为 return 一次只有 50 个结果(会议),并且还能够指定一个参数,该参数采用 nextPageToken 之类的东西来给我接下来的 50 个结果?
我在其他 API 方法中看到过这样做,但似乎无法找到适用于 GAE 或 Cloud Endpoints 的好示例。
- 而不是 returning
List<Conference>
你应该 returncom.google.api.server.spi.response.CollectionResponse<Conference>
. - 添加命名参数,例如
@Named("nextPageToken") String pageToken
。 - 如果
pageToken != null
,在.order()
之后你需要链接.startAt(Cursor.fromWebSafeString(pageToken))
- 您还需要添加
.limit(50)
,因为您希望它成为您的页面大小。 - 而不是
.list()
使用.iterator()
,它有一个getStartCursor()
方法。使用它和迭代器构造CollectionResponse
.
有关如何使用游标的 non-Endpoints 示例,另请参阅 this page。其余的应该是微不足道的。