Files
SIB/frontend/src/services/businessService.ts

83 lines
3.0 KiB
TypeScript

/** Service for business-related API calls */
import { supabase } from '@/supabase'
import type { Business } from '@/types'
export const businessService = {
/** Helper to upload file to supabase storage */
async uploadImage(file: File): Promise<string> {
const fileExt = file.name.split('.').pop()
const fileName = `${Math.random()}-${Date.now()}.${fileExt}`
const filePath = `businesses/${fileName}`
const { error } = await supabase.storage.from('uploads').upload(filePath, file)
if (error) throw new Error(error.message)
const { data } = supabase.storage.from('uploads').getPublicUrl(filePath)
return data.publicUrl
},
/** Get all businesses */
async getAllBusinesses(): Promise<Business[]> {
const { data, error } = await supabase.from('businesses').select('*')
if (error) throw new Error(error.message)
return data as Business[]
},
/** Get a single business by ID */
async getBusiness(id: string): Promise<Business> {
const { data, error } = await supabase.from('businesses').select('*').eq('id', id).single()
if (error) throw new Error(error.message)
return data as Business
},
/** Create a new business */
async createBusiness(businessData: FormData): Promise<Business> {
const payload: any = {}
let fileUpload: File | null = null
businessData.forEach((value, key) => {
if ((key === 'file' || key === 'image') && value instanceof File) {
fileUpload = value
} else if (value !== 'null' && value !== '' && key !== 'file' && key !== 'image') {
payload[key] = value
}
})
if (fileUpload) {
payload.image_url = await this.uploadImage(fileUpload)
}
const { data, error } = await supabase.from('businesses').insert([payload]).select().single()
if (error) throw new Error(error.message)
return data as Business
},
/** Update an existing business */
async updateBusiness(id: string, businessData: FormData): Promise<Business> {
const payload: any = {}
let fileUpload: File | null = null
businessData.forEach((value, key) => {
if ((key === 'file' || key === 'image') && value instanceof File) {
fileUpload = value
} else if (value !== 'null' && value !== '' && key !== 'file' && key !== 'image') {
payload[key] = value
}
})
if (fileUpload) {
payload.image_url = await this.uploadImage(fileUpload)
}
const { data, error } = await supabase.from('businesses').update(payload).eq('id', id).select().single()
if (error) throw new Error(error.message)
return data as Business
},
/** Delete a business */
async deleteBusiness(id: string): Promise<void> {
const { error } = await supabase.from('businesses').delete().eq('id', id)
if (error) throw new Error(error.message)
},
}