Skip to content

Commit 4d5a560

Browse files
committed
Added this simple (and naive) class that implements the AbstractPaginatedData
1 parent 875b290 commit 4d5a560

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package graphql.annotations.connection;
2+
3+
import java.nio.charset.StandardCharsets;
4+
import java.util.Iterator;
5+
6+
import static java.util.Base64.getEncoder;
7+
8+
public class SimplePaginatedData<T> extends AbstractPaginatedData<T> {
9+
private static final String DUMMY_CURSOR_PREFIX = "simple-cursor";
10+
private final String prefix;
11+
12+
public SimplePaginatedData(boolean hasPreviousPage, boolean hasNextPage, Iterable<T> data) {
13+
this(hasPreviousPage, hasNextPage, data, DUMMY_CURSOR_PREFIX);
14+
}
15+
16+
public SimplePaginatedData(boolean hasPreviousPage, boolean hasNextPage, Iterable<T> data, String prefix) {
17+
super(hasPreviousPage, hasNextPage, data);
18+
this.prefix = prefix;
19+
}
20+
21+
/**
22+
* creates the cursor by offset (i.e first entity has cursor 0, the second has 1 and so on)
23+
* NOTE: to make it consistent, please make the data ordered
24+
*
25+
* @param entity the entity
26+
* @return the cursor of the entity (i.e the offset)
27+
*/
28+
@Override
29+
public String getCursor(T entity) {
30+
Iterator<T> iterator = data.iterator();
31+
long offset = 0;
32+
for (; iterator.hasNext(); ) {
33+
T next = iterator.next();
34+
if (entity.equals(next)) {
35+
break;
36+
}
37+
offset++;
38+
}
39+
return createCursor(offset);
40+
}
41+
42+
private String createCursor(long offset) {
43+
byte[] bytes = (prefix + Long.toString(offset)).getBytes(StandardCharsets.UTF_8);
44+
return getEncoder().encodeToString(bytes);
45+
}
46+
}

0 commit comments

Comments
 (0)