67 lines
1.8 KiB
TypeScript
67 lines
1.8 KiB
TypeScript
export const useApi = () => {
|
|
const config = useRuntimeConfig()
|
|
const apiBaseUrl = config.public.apiBaseUrl
|
|
|
|
const getHeaders = () => {
|
|
const headers: Record<string, string> = {
|
|
'Content-Type': 'application/json',
|
|
}
|
|
|
|
// Add tenant ID from localStorage or state
|
|
if (process.client) {
|
|
const tenantId = localStorage.getItem('tenantId')
|
|
if (tenantId) {
|
|
headers['x-tenant-id'] = tenantId
|
|
}
|
|
|
|
const token = localStorage.getItem('token')
|
|
if (token) {
|
|
headers['Authorization'] = `Bearer ${token}`
|
|
}
|
|
}
|
|
|
|
return headers
|
|
}
|
|
|
|
const api = {
|
|
async get(path: string) {
|
|
const response = await fetch(`${apiBaseUrl}/api${path}`, {
|
|
headers: getHeaders(),
|
|
})
|
|
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
|
|
return response.json()
|
|
},
|
|
|
|
async post(path: string, data: any) {
|
|
const response = await fetch(`${apiBaseUrl}/api${path}`, {
|
|
method: 'POST',
|
|
headers: getHeaders(),
|
|
body: JSON.stringify(data),
|
|
})
|
|
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
|
|
return response.json()
|
|
},
|
|
|
|
async put(path: string, data: any) {
|
|
const response = await fetch(`${apiBaseUrl}/api${path}`, {
|
|
method: 'PUT',
|
|
headers: getHeaders(),
|
|
body: JSON.stringify(data),
|
|
})
|
|
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
|
|
return response.json()
|
|
},
|
|
|
|
async delete(path: string) {
|
|
const response = await fetch(`${apiBaseUrl}/api${path}`, {
|
|
method: 'DELETE',
|
|
headers: getHeaders(),
|
|
})
|
|
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
|
|
return response.json()
|
|
},
|
|
}
|
|
|
|
return { api }
|
|
}
|