-
Notifications
You must be signed in to change notification settings - Fork 14
/
Task06b_pagination.ts
44 lines (30 loc) · 1.34 KB
/
Task06b_pagination.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// import { PagedQueryResponse, Product, ProductPagedQueryResponse } from "@commercetools/platform-sdk";
import { getAllProducts, simulatePagination } from "./handson/search";
import { log } from "./utils/logger";
// UseCases
// Fetching ALL products
getAllProducts().then(log).catch(log);
// Fetching ALL products of a certain type
// Fetching ALL orders
// Pagination of some entities BUT only ordered via id
const getPagedQueryResults = async () => {
// Instead of using offset to get a page, ask for products whose ids are greater than the largest id of the
// product in the previous page
const PAGE_SIZE = 2; // How many products per page
let lastId: string, where: string | undefined, seenlastPage: boolean;
do {
// Ask for next page of products
const { results: products, count } = (await simulatePagination(PAGE_SIZE, where)).body;
// Process/print products
log("---- New Page ----");
products.forEach(p => log(p.id));
// Have we processed the last page of products
seenlastPage = count < PAGE_SIZE;
// In case this was not the last page, prepare new query predicate
if (!seenlastPage) {
lastId = products[products.length - 1].id;
where = `id > "${lastId}"`;
}
} while (!seenlastPage)
}
// getPagedQueryResults().catch(log);