From b32b05600980ec70277e0e4d5d2100baa32aae5c Mon Sep 17 00:00:00 2001 From: Manuel Odelain Date: Thu, 14 Mar 2024 22:44:30 +0100 Subject: [PATCH] feat(roadiz): add useRoadizFetch() --- composables/use-roadiz-fetch.ts | 49 +++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 composables/use-roadiz-fetch.ts diff --git a/composables/use-roadiz-fetch.ts b/composables/use-roadiz-fetch.ts new file mode 100644 index 0000000..fbfb254 --- /dev/null +++ b/composables/use-roadiz-fetch.ts @@ -0,0 +1,49 @@ +import type { NitroFetchOptions, NitroFetchRequest } from 'nitropack' + +export function useRoadizFetch( + options?: NitroFetchOptions, +) { + return $fetch.create({ + onRequest(context) { + /* + * Add preview token to every request if preview mode is enabled. + */ + const { token, isActive } = useRoadizPreview() + + if (isActive.value && token.value) { + context.options.query = { + ...context.options.query, + _preview: '1', + } + + context.options.headers = { + ...context.options.headers, + Authorization: `Bearer ${token.value}`, + } + } + /* + * Add locale to every request if it is not a web response request. + */ + if (context.request.toString() !== '/web_response_by_path') { + const { $i18n } = useNuxtApp() + + context.options.query = { + ...context.options.query, + _locale: $i18n?.locale.value || $i18n?.defaultLocale?.toString(), + } + } + }, + onResponseError(context) { + throw createError({ + statusCode: context.response.status, + message: context.response.statusText, + }) + }, + headers: { + 'accept-encoding': 'gzip, deflate', + accept: 'application/ld+json', + }, + baseURL: useApiUrl(), + ...options, + }) +}