From 599b70cd2390d08ce26ee44174b3f39c6587110c Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Mon, 13 Nov 2023 12:37:50 +0100 Subject: refactor(hooks): rewrite usePagination hook * replace `isLoadingInitialData` with `isLoading` & `isRefreshing` * rename `fallbackData` prop to `fallback` * replace `setSize` return with a `loadMore` callback * add tests --- tests/utils/graphql/connections.ts | 54 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 tests/utils/graphql/connections.ts (limited to 'tests/utils/graphql/connections.ts') 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>} The edges. + */ +export const getEdges = (data: T[], offset: number): GraphQLEdges[] => + data.map((singleData, index) => { + const currentItemNumber = index + 1; + + return { + cursor: `cursor${currentItemNumber + offset}`, + node: singleData, + }; + }); + +type GetConnectionProps = { + data: Maybe; + first: Maybe; + after: Maybe; +}; + +/** + * 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} The connection. + */ +export const getConnection = ({ + after, + data = [], + first = settings.postsPerPage, +}: GetConnectionProps): EdgesResponse => { + 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, + }, + }; +}; -- cgit v1.2.3