34 lines
1,010 B
TypeScript
34 lines
1,010 B
TypeScript
import type { UseFetchOptions } from 'nuxt/app';
|
|
|
|
export const useApi = () => {
|
|
const config = useRuntimeConfig();
|
|
const baseURL = config.public.apiBaseUrl as string;
|
|
|
|
const apiFetch = <T>(url: string, options?: UseFetchOptions<T>) => {
|
|
return $fetch<T>(url, {
|
|
baseURL,
|
|
...options,
|
|
headers: {
|
|
...options?.headers,
|
|
},
|
|
onRequest({ options }) {
|
|
// Add auth token if available
|
|
const token = localStorage.getItem('token');
|
|
if (token) {
|
|
options.headers = {
|
|
...options.headers,
|
|
Authorization: `Bearer ${token}`
|
|
};
|
|
}
|
|
},
|
|
onResponseError({ response }) {
|
|
// Handle errors globally
|
|
console.error('API Error:', response.status, response._data);
|
|
}
|
|
});
|
|
};
|
|
|
|
return {
|
|
apiFetch
|
|
};
|
|
};
|