Closed spencerjsmall closed 1 day ago
Hi there,
I'm glad that you want to use my library for your Nuxt 3 project. Since useFetchModel uses the ofetch library (https://github.com/unjs/ofetch and https://nuxt.com/docs/api/composables/use-fetch), you can easily set it up like this:
File: _utils.ts
export function getEcomFetchOption(): Partial<FetchOptions> {
const { loggedIn } = useUserSession()
const { locale } = useI18n()
const { $configuration } = useNuxtApp()
const config = useRuntimeConfig()
return {
baseURL: config.public.apiBaseUrl,
onRequest: (context) => {
context.options.headers = {
...(context.options.headers || {}),
'Accept-Language': locale.value,
'Custom-Header': 'Custom value'
}
}
}
}
For example, this method is then used in all the composables in the API folder where I need custom headers.
Example of usage:
export default function () {
const { useFetch } = useFetchModel(getEcomFetchOption())
return {
findById: async (id: number) => {
const response = await useFetch.get<Product>(`/products/${id}`, {
key: `ecom-product-${id}`
})
if (response.error.value) {
throw showError({
statusCode: 404,
statusMessage: response.error.value.statusMessage,
message: response.error.value.message
})
}
return response
}
}
}
Don't hesitate to add a star ;)
Thank you! Exactly what i needed.
Hey! Super pumped on trying out this library. I'm wondering if it's possible, either globally or through the
useFetchModel
composable, to set default headers (such as authorization, etc.). Thanks! For context, I'm building with Nuxt 3.