diff options
| author | Armand Philippot <git@armandphilippot.com> | 2023-11-13 12:37:50 +0100 |
|---|---|---|
| committer | Armand Philippot <git@armandphilippot.com> | 2023-11-13 15:36:38 +0100 |
| commit | 599b70cd2390d08ce26ee44174b3f39c6587110c (patch) | |
| tree | 15d967fc142bf632df3dd55df373bfd4e33d2d90 /tests/utils/graphql/connections.ts | |
| parent | d7bcd93efcd4f1ae20678d0efa6777cfadc09a4e (diff) | |
refactor(hooks): rewrite usePagination hook
* replace `isLoadingInitialData` with `isLoading` & `isRefreshing`
* rename `fallbackData` prop to `fallback`
* replace `setSize` return with a `loadMore` callback
* add tests
Diffstat (limited to 'tests/utils/graphql/connections.ts')
| -rw-r--r-- | tests/utils/graphql/connections.ts | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/tests/utils/graphql/connections.ts b/tests/utils/graphql/connections.ts new file mode 100644 index 0000000..d1c3b93 --- /dev/null +++ b/tests/utils/graphql/connections.ts @@ -0,0 +1,54 @@ +import type { EdgesResponse, GraphQLEdges, Maybe } from '../../../src/types'; +import { settings } from '../../../src/utils/config'; + +/** + * Retrieve the edges. + * + * @param {T[]} data - An array of objects. + * @param {number} offset - The offset. + * @returns {Array<Edge<T>>} The edges. + */ +export const getEdges = <T>(data: T[], offset: number): GraphQLEdges<T>[] => + data.map((singleData, index) => { + const currentItemNumber = index + 1; + + return { + cursor: `cursor${currentItemNumber + offset}`, + node: singleData, + }; + }); + +type GetConnectionProps<T> = { + data: Maybe<T[]>; + first: Maybe<number>; + after: Maybe<string>; +}; + +/** + * Retrieve a GraphQL connection. + * + * @param props - An object. + * @param props.after - The number of items before. + * @param props.data - An array of items. + * @param props.first - The number of items per page. + * @returns {Connection<T>} The connection. + */ +export const getConnection = <T>({ + after, + data = [], + first = settings.postsPerPage, +}: GetConnectionProps<T>): EdgesResponse<T> => { + const afterInt = after ? Number(after.replace('cursor', '')) : 0; + const edges = getEdges(data.slice(afterInt, afterInt + first), afterInt); + const endCursor = + edges.length > 0 ? edges[edges.length - 1].cursor : 'cursor1'; + + return { + edges, + pageInfo: { + endCursor, + hasNextPage: data.length - afterInt > first, + total: data.length, + }, + }; +}; |
