2023-07-20 11:19:42 -07:00
|
|
|
export const useBaseFetch = async (url, options = {}, skipAuth = false) => {
|
2025-08-14 21:48:38 +01:00
|
|
|
const config = useRuntimeConfig()
|
|
|
|
|
let base = import.meta.server ? config.apiBaseUrl : config.public.apiBaseUrl
|
2023-03-09 10:05:32 -07:00
|
|
|
|
2025-08-14 21:48:38 +01:00
|
|
|
if (!options.headers) {
|
|
|
|
|
options.headers = {}
|
|
|
|
|
}
|
2023-07-20 11:19:42 -07:00
|
|
|
|
2025-08-14 21:48:38 +01:00
|
|
|
if (import.meta.server) {
|
|
|
|
|
options.headers['x-ratelimit-key'] = config.rateLimitKey
|
|
|
|
|
}
|
2023-07-20 11:19:42 -07:00
|
|
|
|
2025-08-14 21:48:38 +01:00
|
|
|
if (!skipAuth) {
|
|
|
|
|
const auth = await useAuth()
|
2023-07-20 11:19:42 -07:00
|
|
|
|
2025-08-14 21:48:38 +01:00
|
|
|
options.headers.Authorization = auth.value.token
|
|
|
|
|
}
|
2023-03-09 10:05:32 -07:00
|
|
|
|
2025-08-14 21:48:38 +01:00
|
|
|
if (options.apiVersion || options.internal) {
|
|
|
|
|
// Base may end in /vD/ or /vD. We would need to replace the digit with the new version number
|
|
|
|
|
// and keep the trailing slash if it exists
|
|
|
|
|
const baseVersion = base.match(/\/v\d\//)
|
2023-12-04 19:26:50 -08:00
|
|
|
|
2025-08-14 21:48:38 +01:00
|
|
|
const replaceStr = options.internal ? `/_internal/` : `/v${options.apiVersion}/`
|
2023-12-04 19:26:50 -08:00
|
|
|
|
2025-08-14 21:48:38 +01:00
|
|
|
if (baseVersion) {
|
|
|
|
|
base = base.replace(baseVersion[0], replaceStr)
|
|
|
|
|
} else {
|
|
|
|
|
base = base.replace(/\/v\d$/, replaceStr)
|
|
|
|
|
}
|
2023-12-04 19:26:50 -08:00
|
|
|
|
2025-08-14 21:48:38 +01:00
|
|
|
delete options.apiVersion
|
|
|
|
|
}
|
2023-12-04 19:26:50 -08:00
|
|
|
|
2025-08-14 21:48:38 +01:00
|
|
|
return await $fetch(`${base}${url}`, options)
|
|
|
|
|
}
|