Init
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
import {useAppStore} from "@/stores/app";
|
||||
import {useAuthStore} from "@/stores/auth";
|
||||
|
||||
export function useApi() {
|
||||
const appStore = useAppStore()
|
||||
const authStore = useAuthStore()
|
||||
const baseUrl = `${appStore.baseurl}/api`
|
||||
|
||||
const request = async (endpoint: string, options: RequestInit = {}) => {
|
||||
const headers = new Headers(options.headers)
|
||||
|
||||
if (!headers.has('Content-Type')) {
|
||||
headers.set('Content-Type', 'application/json')
|
||||
}
|
||||
|
||||
if (authStore.token) {
|
||||
headers.set('Authorization', `Bearer ${authStore.token}`)
|
||||
}
|
||||
|
||||
const config = {
|
||||
...options,
|
||||
headers,
|
||||
body: options.body && typeof options.body === 'object'
|
||||
? JSON.stringify(options.body)
|
||||
: options.body
|
||||
}
|
||||
|
||||
// Ici on ne fait QUE la requête.
|
||||
// On laisse l'appelant décider de ce qu'il fait du status (401, 404, etc.)
|
||||
return fetch(`${baseUrl}${endpoint}`, config)
|
||||
}
|
||||
|
||||
return {
|
||||
request,
|
||||
get: (url: string, options?: RequestInit) =>
|
||||
request(url, {...options, method: 'GET'}),
|
||||
|
||||
post: (url: string, data?: any, options?: RequestInit) =>
|
||||
request(url, {...options, method: 'POST', body: data}),
|
||||
|
||||
put: (url: string, data?: any, options?: RequestInit) =>
|
||||
request(url, {...options, method: 'PUT', body: data}),
|
||||
|
||||
delete: (url: string, options?: RequestInit) =>
|
||||
request(url, {...options, method: 'DELETE'}),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user