useApi.js
860 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { createFetch } from '@vueuse/core'
import { destr } from 'destr'
export const useApi = createFetch({
baseUrl: import.meta.env.VITE_API_BASE_URL || '/api',
fetchOptions: {
headers: {
Accept: 'application/json',
},
},
options: {
refetch: true,
async beforeFetch({ options }) {
const accessToken = useCookie('accessToken').value
if (accessToken) {
options.headers = {
...options.headers,
Authorization: `Bearer ${accessToken}`,
}
}
return { options }
},
afterFetch(ctx) {
const { data, response } = ctx
// Parse data if it's JSON
let parsedData = null
try {
parsedData = destr(data)
}
catch (error) {
console.error(error)
}
return { data: parsedData, response }
},
},
})