|
| 1 | +package io.weaviate.client6.v1.api.collections.pagination; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.Iterator; |
| 6 | +import java.util.List; |
| 7 | +import java.util.concurrent.CompletableFuture; |
| 8 | +import java.util.function.BiFunction; |
| 9 | + |
| 10 | +import io.weaviate.client6.v1.api.collections.WeaviateObject; |
| 11 | +import io.weaviate.client6.v1.api.collections.query.QueryMetadata; |
| 12 | + |
| 13 | +public final class AsyncPage<PropertiesT> implements Iterable<WeaviateObject<PropertiesT, Object, QueryMetadata>> { |
| 14 | + |
| 15 | + private final int pageSize; |
| 16 | + private final BiFunction<String, Integer, CompletableFuture<List<WeaviateObject<PropertiesT, Object, QueryMetadata>>>> fetch; |
| 17 | + |
| 18 | + private final String cursor; |
| 19 | + private List<WeaviateObject<PropertiesT, Object, QueryMetadata>> currentPage = new ArrayList<>(); |
| 20 | + |
| 21 | + AsyncPage(String cursor, int pageSize, |
| 22 | + BiFunction<String, Integer, CompletableFuture<List<WeaviateObject<PropertiesT, Object, QueryMetadata>>>> fetch) { |
| 23 | + this.cursor = cursor; |
| 24 | + this.pageSize = pageSize; |
| 25 | + this.fetch = fetch; |
| 26 | + } |
| 27 | + |
| 28 | + AsyncPage(String cursor, int pageSize, |
| 29 | + BiFunction<String, Integer, CompletableFuture<List<WeaviateObject<PropertiesT, Object, QueryMetadata>>>> fetch, |
| 30 | + List<WeaviateObject<PropertiesT, Object, QueryMetadata>> currentPage) { |
| 31 | + this(cursor, pageSize, fetch); |
| 32 | + this.currentPage = Collections.unmodifiableList(currentPage); |
| 33 | + } |
| 34 | + |
| 35 | + List<WeaviateObject<PropertiesT, Object, QueryMetadata>> items() { |
| 36 | + return currentPage; |
| 37 | + } |
| 38 | + |
| 39 | + public boolean isEmpty() { |
| 40 | + return this.currentPage.isEmpty(); |
| 41 | + } |
| 42 | + |
| 43 | + public CompletableFuture<AsyncPage<PropertiesT>> fetchNextPage() { |
| 44 | + return fetch.apply(cursor, pageSize) |
| 45 | + .thenApply(nextPage -> { |
| 46 | + if (nextPage.isEmpty()) { |
| 47 | + return new AsyncPage<>(null, pageSize, fetch, nextPage); |
| 48 | + } |
| 49 | + var last = nextPage.get(nextPage.size() - 1); |
| 50 | + return new AsyncPage<>(last.metadata().uuid(), pageSize, fetch, nextPage); |
| 51 | + }); |
| 52 | + } |
| 53 | + |
| 54 | + @Override |
| 55 | + public Iterator<WeaviateObject<PropertiesT, Object, QueryMetadata>> iterator() { |
| 56 | + return currentPage.iterator(); |
| 57 | + } |
| 58 | +} |
0 commit comments