UNPKG

nuxt-kql

Version:

Kirby's Query Language API for Nuxt

95 lines (94 loc) 2.6 kB
import { useAsyncData, useRequestFetch, useRuntimeConfig } from "#imports"; import { hash } from "ohash"; import { joinURL } from "ufo"; import { computed, toValue } from "vue"; import { createAuthHeader, getProxyPath, headersToObject } from "../utils.js"; export function useKirbyData(path, opts = {}) { const { server, lazy, default: defaultFn, transform, pick, watch: watchSources, immediate, query, headers, method, body, language, cache = true, ...fetchOptions } = opts; const kql = useRuntimeConfig().public.kql; const _language = computed(() => toValue(language)); const _path = computed(() => { const value = toValue(path).replace(/^\//, ""); return _language.value ? joinURL(_language.value, value) : value; }); const key = computed(() => `$kirby${hash([ _path.value, query, method ])}`); if (!_path.value || _language.value && !_path.value.replace(new RegExp(`^${_language.value}/`), "")) console.warn("[useKirbyData] Empty Kirby path"); const asyncDataOptions = { server, lazy, default: defaultFn, transform, pick, watch: watchSources === false ? [] : [...watchSources || [], key], immediate }; let controller; return useAsyncData( watchSources === false ? key.value : key, async (nuxt) => { controller?.abort?.(); if (nuxt && (nuxt.isHydrating || cache) && nuxt.payload.data[key.value]) return nuxt.payload.data[key.value]; controller = new AbortController(); try { let result; if (kql.client) { result = await useRequestFetch()(_path.value, { ...fetchOptions, signal: controller.signal, baseURL: kql.url, query, headers: { ...headersToObject(headers), ...createAuthHeader(kql) }, method, body }); } else { result = await useRequestFetch()(getProxyPath(key.value), { ...fetchOptions, signal: controller.signal, method: "POST", body: { path: _path.value, query, headers: headersToObject(headers), method, body, cache } }); } if (nuxt && cache) nuxt.payload.data[key.value] = result; return result; } catch (error) { if (nuxt) nuxt.payload.data[key.value] = void 0; throw error; } }, asyncDataOptions ); }