Last active
September 20, 2023 07:23
-
-
Save johannschopplich/b4c368e17dd6469aea39d03d0f2b84ee to your computer and use it in GitHub Desktop.
Vue composable to fetch KQL queries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { $fetch } from "ofetch"; | |
import { hash } from "ohash"; | |
import { toValue } from "@vueuse/core"; | |
import { useQuery } from "vue-unquery"; | |
import { useI18n } from "@byjohann/vue-i18n"; | |
import type { MaybeRefOrGetter } from "@vueuse/core"; | |
import type { TurboVueOptions } from "vue-unquery"; | |
import type { KirbyQueryRequest, KirbyQueryResponse } from "kirby-types"; | |
let responseCache: KirbyQueryResponse | undefined; | |
export function useKqlContext<T = any, Pagination extends boolean = false>() { | |
return { | |
response: responseCache as KirbyQueryResponse<T, Pagination> | undefined, | |
}; | |
} | |
export function useKql< | |
T = any, | |
Pagination extends boolean = false, | |
ReqT extends KirbyQueryRequest = KirbyQueryRequest, | |
>( | |
query: MaybeRefOrGetter<ReqT>, | |
options: TurboVueOptions & { language?: string } = {}, | |
) { | |
const { language, ...turboVueOptions } = options; | |
// Instance may be `undefined` between HMR updates | |
const i18n = useI18n(); | |
return useQuery<KirbyQueryResponse<T, Pagination>>( | |
() => hash(toValue(query)), | |
{ | |
...turboVueOptions, | |
refetchOnFocus: false, | |
fetcher(_key, { signal }) { | |
return $kql<KirbyQueryResponse<T, Pagination>>(toValue(query), { | |
signal, | |
language: language || i18n?.locale?.value, | |
}); | |
}, | |
}, | |
); | |
} | |
export function $kql< | |
T = any, | |
Pagination extends boolean = false, | |
ReqT extends KirbyQueryRequest = KirbyQueryRequest, | |
>( | |
query: ReqT, | |
{ signal, language }: { signal?: AbortSignal; language?: string } = {}, | |
) { | |
const { api } = useRuntimeConfig().public; | |
return $fetch<KirbyQueryResponse<T, Pagination>>("api/kql", { | |
baseURL: api.baseUrl, | |
method: "POST", | |
body: query, | |
headers: { | |
Authorization: `Bearer ${api.token}`, | |
...(language && { "X-Language": language }), | |
}, | |
signal, | |
async onRequestError({ request }) { | |
console.error("[$kql] Request error:", request); | |
}, | |
async onResponseError({ response }) { | |
console.error("[$kql] Response error:", response); | |
}, | |
async onResponse({ error, response }) { | |
responseCache = error ? undefined : response._data; | |
}, | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment