【问题标题】:Google App Engine query 50 results at a time with a nextPageTokenGoogle App Engine 使用 nextPageToken 一次查询 50 个结果
【发布时间】:2016-01-08 00:15:55
【问题描述】:

我的 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; 

}

它工作得很好,并为我返回给定用户创建的所有会议,按日期排序。 Conference 类具有以下属性来指定它有一个 User 父类:

@Parent
private Key<User> userKey;

我的问题是,如何更改上述方法以一次仅返回 50 个结果(会议),并且还能够指定一个参数,该参数采用 nextPageToken 之类的参数来给我接下来的 50 个结果?

我已经在其他 API 方法中看到了这一点,但似乎找不到一个很好的 GAE 或 Cloud Endpoints 示例。

【问题讨论】:

    标签: google-app-engine google-cloud-endpoints objectify


    【解决方案1】:
    1. 您应该返回com.google.api.server.spi.response.CollectionResponse&lt;Conference&gt;,而不是返回List&lt;Conference&gt;
    2. 添加命名参数,如@Named("nextPageToken") String pageToken
    3. 如果pageToken != null,在.order()之后你需要链接.startAt(Cursor.fromWebSafeString(pageToken))
    4. 您还需要添加.limit(50),因为您希望它成为您的页面大小。
    5. 使用.iterator() 代替.list(),它有一个getStartCursor() 方法。使用这个和迭代器来构造CollectionResponse

    另请参阅this page,了解如何使用游标的非端点示例。其余的应该是微不足道的。

    【讨论】:

    • 谢谢你,先生,我会用你给我的东西工作。为什么要使用 CollectionResponse 而不是 List?
    • CollectionResponse 包含一个用于下一页标记的字段。它只是一个包装类。
    猜你喜欢
    • 2013-03-23
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多