api-client/packages/hoppscotch-sh-admin/src/composables/useClientHandler.ts
Joel Jacob Stephen 3d6adcc39d
refactor: consolidated admin dashboard improvements (#3790)
Co-authored-by: jamesgeorge007 <jamesgeorge998001@gmail.com>
2024-02-02 15:17:25 +05:30

54 lines
1.3 KiB
TypeScript

import { TypedDocumentNode, useClientHandle } from '@urql/vue';
import { DocumentNode } from 'graphql';
import { Ref, ref } from 'vue';
/** A composable function to handle grapqhl requests
* using urql's useClientHandle
* @param query The query to be executed
* @param getList A function to get the list from the result
* @param variables The variables to be passed to the query
*/
export function useClientHandler<
Result,
Vars extends Record<string, any>,
ListItem
>(
query: string | TypedDocumentNode<Result, Vars> | DocumentNode,
variables: Vars,
getList?: (result: Result) => ListItem[]
) {
const { client } = useClientHandle();
const fetching = ref(true);
const error = ref(false);
const data = ref<Result>();
const dataAsList: Ref<ListItem[]> = ref([]);
const fetchData = async () => {
fetching.value = true;
try {
const result = await client
.query(query, {
...variables,
})
.toPromise();
if (getList) {
const resultList = getList(result.data!);
dataAsList.value.push(...resultList);
} else {
data.value = result.data;
}
} catch (e) {
error.value = true;
}
fetching.value = false;
};
return {
fetching,
error,
data,
dataAsList,
fetchData,
};
}