From b90f44dd5ec135304d7e3e674bb8892e4b2a5862 Mon Sep 17 00:00:00 2001 From: Tai Sakuma Date: Mon, 25 Sep 2023 16:11:41 -0400 Subject: [PATCH] clean code --- src/utils/query-state.ts | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/utils/query-state.ts b/src/utils/query-state.ts index 3e70bdc..8be98f9 100644 --- a/src/utils/query-state.ts +++ b/src/utils/query-state.ts @@ -1,4 +1,5 @@ import { ref, computed, watch } from "vue"; +import type { Ref } from "vue"; import { useStore } from "@/plugins/pinia/stores/main"; import type { UseQueryResponse, AnyVariables } from "@urql/vue"; import { refThrottled } from "@vueuse/core"; @@ -15,28 +16,29 @@ export function useQueryState( options: UseQueryStateOptions = {} ) { const { isNull, isEmpty } = options; + const executeQuery = async () => + await query.executeQuery({ requestPolicy: "network-only" }); - useExecuteQueryOnMutation(query); + useExecuteQueryOnMutation(executeQuery); - const state = useState(query, isEmpty, isNull); + const state = useState(query, executeQuery, isEmpty, isNull); return { ...state }; } -function useExecuteQueryOnMutation( - query: UseQueryResponse -) { +function useExecuteQueryOnMutation(executeQuery: () => Promise) { const store = useStore(); watch( () => store.nApolloMutations, - () => { - query.executeQuery({ requestPolicy: "network-only" }); + async () => { + await executeQuery(); } ); } function useState( query: UseQueryResponse, + executeQuery: () => Promise, isEmpty: ((query: UseQueryResponse) => boolean) | undefined, isNull: ((query: UseQueryResponse) => boolean) | undefined ) { @@ -47,7 +49,7 @@ function useState( const error = useError(query); - const { refreshing, refresh } = useRefresh(query); + const { refreshing, refresh } = useRefresh(executeQuery); const state = computed(() => { if (devtoolState.value !== "off") return devtoolState.value; @@ -71,7 +73,7 @@ function useState( }; } -function useError(query: UseQueryResponse) { +function useError(query: { error: Ref }) { const error = ref(null); watch(query.error, (e) => { error.value = e?.message || null; @@ -79,7 +81,7 @@ function useError(query: UseQueryResponse) { return error; } -function useRefresh(query: UseQueryResponse) { +function useRefresh(executeQuery: () => Promise) { const _refreshing = ref(false); // Throttle so as to avoid flickering @@ -87,7 +89,7 @@ function useRefresh(query: UseQueryResponse) { async function refresh() { _refreshing.value = true; - await query.executeQuery({ requestPolicy: "network-only" }); + await executeQuery(); _refreshing.value = false; }