forked from NdoleStudio/httpsms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseApi.ts
More file actions
45 lines (38 loc) · 1017 Bytes
/
Copy pathuseApi.ts
File metadata and controls
45 lines (38 loc) · 1017 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
40
41
42
43
44
45
import type { $Fetch } from 'ofetch'
let authToken: string | null = null
let apiKey: string | null = null
export function setAuthHeader(token: string | null) {
authToken = token
}
export function setApiKey(key: string | null) {
apiKey = key
}
function createApiFetch(): $Fetch {
const config = useRuntimeConfig()
const publicConfig = config.public as Record<string, string>
const baseURL = publicConfig.apiBaseUrl
return $fetch.create({
baseURL,
headers: {
'X-Client-Version': publicConfig.clientVersion || 'dev',
},
onRequest({ options }) {
const headers = new Headers(options.headers)
if (authToken) {
headers.set('Authorization', `Bearer ${authToken}`)
}
if (apiKey) {
headers.set('x-api-key', apiKey)
}
options.headers = headers
},
})
}
export function useApi() {
return { apiFetch: createApiFetch(), setAuthHeader, setApiKey }
}
export function useApiComposable() {
return {
useApi: createApiFetch,
}
}