0
votes

I want to return a List of "Posts" from an endpoint with optional pagination. I need 100 results per query. The Code i have written is as follows, it doesn't seem to work. I am referring to an example at Objectify Wiki

Another option i know of is using query.offset(100); But i read somewhere that this just loads the entire table and then ignores the first 100 entries which is not optimal.

I guess this must be a common use case and an optimal solution will be available.

public CollectionResponse<Post> getPosts(@Nullable @Named("cursor") String cursor,User auth) throws OAuthRequestException {
        if (auth!=null){

            Query<Post> query = ofy().load().type(Post.class).filter("isReviewed", true).order("-timeStamp").limit(100);

            if (cursor!=null){
                query.startAt(Cursor.fromWebSafeString(cursor));
                log.info("Cursor received :" + Cursor.fromWebSafeString(cursor));
            } else {
                log.info("Cursor received : null");
            }

            QueryResultIterator<Post> iterator = query.iterator();

            for (int i = 1 ; i <=100 ; i++){
                if (iterator.hasNext()) iterator.next();
                else break;
            }

            log.info("Cursor generated :" + iterator.getCursor());

            return CollectionResponse.<Post>builder().setItems(query.list()).setNextPageToken(iterator.getCursor().toWebSafeString()).build();

        } else throw new OAuthRequestException("Login please.");
    }

This is a code using Offsets which seems to work fine.

@ApiMethod(
            name = "getPosts",
            httpMethod = ApiMethod.HttpMethod.GET
    )
    public CollectionResponse<Post> getPosts(@Nullable @Named("offset") Integer offset,User auth) throws OAuthRequestException {
        if (auth!=null){

            if (offset==null) offset = 0;

            Query<Post> query = ofy().load().type(Post.class).filter("isReviewed", true).order("-timeStamp").offset(offset).limit(LIMIT);

            log.info("Offset received :" + offset);
            log.info("Offset generated :" + (LIMIT+offset));

            return CollectionResponse.<Post>builder().setItems(query.list()).setNextPageToken(String.valueOf(LIMIT + offset)).build();

        } else throw new OAuthRequestException("Login please.");
    }
2

2 Answers

1
votes

Be sure to assign the query:

query = query.startAt(cursor);

Objectify's API uses a functional style. startAt() does not mutate the object.

0
votes

Try the following:

  1. Remove your for loop -- not sure why it is there. But just iterate through your list and build out the list of items that you want to send back. You should stick to the iterator and not force it for 100 items in a loop.
  2. Next, once you have iterated through it, use the iterator.getStartCursor() as the value of the cursor.