Skip to content

Commit

Permalink
feat(roadiz): add useRoadizFetch()
Browse files Browse the repository at this point in the history
  • Loading branch information
manuelodelain committed Mar 14, 2024
1 parent 0cfbb18 commit b32b056
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions composables/use-roadiz-fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import type { NitroFetchOptions, NitroFetchRequest } from 'nitropack'

export function useRoadizFetch<DefaultR extends NitroFetchRequest = NitroFetchRequest>(
options?: NitroFetchOptions<DefaultR>,
) {
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,
})
}

0 comments on commit b32b056

Please sign in to comment.