Skip to content

Instantly share code, notes, and snippets.

@nrchandan
Last active July 5, 2021 17:16
Show Gist options
  • Save nrchandan/7ca30558866cebdbb75821cd2634f90c to your computer and use it in GitHub Desktop.
Save nrchandan/7ca30558866cebdbb75821cd2634f90c to your computer and use it in GitHub Desktop.
public class ProductClient {
public ProductClient(Configuration config, RestTemplate restTemplate) {
...
}
public Iterator<List<Product>> fetchAllProducts() {
return new ResponseIterator();
}
private class ResponseIterator implements Iterator<List<Product>> {
private String nextPage;
public ResponseIterator() {
nextPage = "/products";
}
@Override
public boolean hasNext() {
return nextPage != null;
}
@Override
public List<Product> next() {
if (!hasNext()) {
throw new NoSuchElementException("Reached the last page of the API response.");
}
ResponseEntity<ProductsResponse> entity = invokeGetAllProductsEndpoint(nextPage);
nextPage = entity.getBody().getNextPageRequestPath();
List<Product> ProductsInThisPage = entity.getBody().getProducts();
return ProductsInThisPage;
}
}
private ResponseEntity<ReviewsResponse> invokeGetAllProductsEndpoint(String endPoint) {
String url = "https://example.com" + endPoint;
return restTemplate.getForEntity(url, ProductsResponse.class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment