Added basic crud for objects
This commit is contained in:
@@ -63,15 +63,63 @@ export const useApi = () => {
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`)
|
||||
// Try to get error details from response
|
||||
const text = await response.text()
|
||||
console.error('API Error Response:', {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
body: text
|
||||
})
|
||||
|
||||
let errorMessage = `HTTP error! status: ${response.status}`
|
||||
if (text) {
|
||||
try {
|
||||
const errorData = JSON.parse(text)
|
||||
errorMessage = errorData.message || errorData.error || errorMessage
|
||||
} catch (e) {
|
||||
// If not JSON, use the text directly if it's not too long
|
||||
if (text.length < 200) {
|
||||
errorMessage = text
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(errorMessage)
|
||||
}
|
||||
|
||||
return response.json()
|
||||
// Handle empty responses
|
||||
const text = await response.text()
|
||||
if (!text) {
|
||||
return {}
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(text)
|
||||
} catch (e) {
|
||||
console.error('Failed to parse JSON response:', text)
|
||||
throw new Error('Invalid JSON response from server')
|
||||
}
|
||||
}
|
||||
|
||||
const api = {
|
||||
async get(path: string) {
|
||||
const response = await fetch(`${getApiBaseUrl()}/api${path}`, {
|
||||
async get(path: string, options?: { params?: Record<string, any> }) {
|
||||
let url = `${getApiBaseUrl()}/api${path}`
|
||||
|
||||
// Add query parameters if provided
|
||||
if (options?.params) {
|
||||
const searchParams = new URLSearchParams()
|
||||
Object.entries(options.params).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null) {
|
||||
searchParams.append(key, String(value))
|
||||
}
|
||||
})
|
||||
const queryString = searchParams.toString()
|
||||
if (queryString) {
|
||||
url += `?${queryString}`
|
||||
}
|
||||
}
|
||||
|
||||
const response = await fetch(url, {
|
||||
headers: getHeaders(),
|
||||
})
|
||||
return handleResponse(response)
|
||||
|
||||
Reference in New Issue
Block a user