-
Notifications
You must be signed in to change notification settings - Fork 71
/
buildPaginatedQueryResult.ts
74 lines (61 loc) · 1.56 KB
/
buildPaginatedQueryResult.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { PaginatedResultInfoFragment } from '../graphql/fragments.generated';
export type PaginatedQueryData<Item> = {
pageInfo: PaginatedResultInfoFragment;
items: Item[];
};
/**
* A paginated query result.
*/
export type PaginatedResult<T> = PaginatedQueryData<T> & {
/**
* Fetch the next page of items.
*
* @returns A promise that resolves when the next page of items has been fetched.
*/
next(): Promise<PaginatedResult<T> | null>;
/**
* Fetch the previous page of items.
*
* @returns A promise that resolves when the previous page of items has been fetched.
*/
prev(): Promise<PaginatedResult<T> | null>;
};
/**
* @internal
*/
export async function buildPaginatedQueryResult<V, R>(
queryFn: (variables: V) => Promise<PaginatedQueryData<R>>,
variables: V,
): Promise<PaginatedResult<R>> {
let result = await queryFn(variables);
return {
get pageInfo() {
return result.pageInfo;
},
get items() {
return result.items;
},
async next() {
if (result.pageInfo.next) {
const nextResult = await buildPaginatedQueryResult(queryFn, {
...variables,
cursor: result.pageInfo.next,
});
result = nextResult;
return nextResult;
}
return null;
},
async prev() {
if (result.pageInfo.prev) {
const prevResult = await buildPaginatedQueryResult(queryFn, {
...variables,
cursor: result.pageInfo.prev,
});
result = prevResult;
return prevResult;
}
return null;
},
};
}