Skip to content

Commit

Permalink
refactor: improvements to paged query
Browse files Browse the repository at this point in the history
  • Loading branch information
JoelJacobStephen committed Mar 7, 2024
1 parent 433a79d commit 6ebf8a9
Showing 1 changed file with 22 additions and 17 deletions.
39 changes: 22 additions & 17 deletions packages/hoppscotch-sh-admin/src/composables/usePagedQuery.ts
@@ -1,4 +1,4 @@
import { Ref, onMounted, ref } from 'vue';
import { onMounted, ref, Ref } from 'vue';
import { DocumentNode } from 'graphql';
import { TypedDocumentNode, useClientHandle } from '@urql/vue';

Expand All @@ -9,9 +9,9 @@ export function usePagedQuery<
>(
query: string | TypedDocumentNode<Result, Vars> | DocumentNode,
getList: (result: Result) => ListItem[],
getCursor: (value: ListItem) => string,
itemsPerPage: number,
variables: Vars
variables: Vars,
getCursor?: (value: ListItem) => string
) {
const { client } = useClientHandle();
const fetching = ref(true);
Expand All @@ -20,21 +20,23 @@ export function usePagedQuery<
const currentPage = ref(0);
const hasNextPage = ref(true);

const fetchNextPage = async () => {
const fetchNextPage = async (additionalVariables?: Vars) => {
fetching.value = true;

const cursor =
list.value.length > 0 ? getCursor(list.value.at(-1)!) : undefined;
const variablesForPagination = {
...variables,
take: itemsPerPage,
cursor,
};

const result = await client
.query(query, variablesForPagination)
.toPromise();
// Cursor based pagination
if (getCursor) {
const cursor =
list.value.length > 0
? getCursor(list.value.at(-1) as ListItem)
: undefined;
variables = { ...variables, cursor };
}
// Offset based pagination
else if (additionalVariables) {
variables = { ...variables, ...additionalVariables };
}

const result = await client.query(query, { ...variables }).toPromise();
if (result.error) {
error.value = true;
fetching.value = false;
Expand Down Expand Up @@ -63,11 +65,14 @@ export function usePagedQuery<
}
};

const refetch = async () => {
const refetch = async (variables?: Vars) => {
currentPage.value = 0;
hasNextPage.value = true;
list.value = [];
await fetchNextPage();

if (hasNextPage.value) {
variables ? await fetchNextPage(variables) : await fetchNextPage();
}
};

return {
Expand Down

0 comments on commit 6ebf8a9

Please sign in to comment.