| 1 | function getBaseUrl(): string {
|
|---|
| 2 | const base = (import.meta.env.VITE_API_BASE_URL as string | undefined) ?? ''
|
|---|
| 3 | return base.replace(/\/$/, '')
|
|---|
| 4 | }
|
|---|
| 5 |
|
|---|
| 6 | function joinUrl(base: string, path: string): string {
|
|---|
| 7 | if (!base) return path
|
|---|
| 8 | return `${base}${path.startsWith('/') ? '' : '/'}${path}`
|
|---|
| 9 | }
|
|---|
| 10 |
|
|---|
| 11 | export async function addFavorite(userId: number, listingId: number): Promise<void> {
|
|---|
| 12 | const url = joinUrl(getBaseUrl(), `/api/favorites/${listingId}`)
|
|---|
| 13 | const response = await fetch(url, {
|
|---|
| 14 | method: 'POST',
|
|---|
| 15 | headers: {
|
|---|
| 16 | 'Content-Type': 'application/json',
|
|---|
| 17 | 'X-User-Id': String(userId),
|
|---|
| 18 | },
|
|---|
| 19 | })
|
|---|
| 20 |
|
|---|
| 21 | if (!response.ok) {
|
|---|
| 22 | const error = await response.json()
|
|---|
| 23 | throw new Error(error.error || 'Failed to add favorite')
|
|---|
| 24 | }
|
|---|
| 25 | }
|
|---|
| 26 |
|
|---|
| 27 | export async function removeFavorite(userId: number, listingId: number): Promise<void> {
|
|---|
| 28 | const url = joinUrl(getBaseUrl(), `/api/favorites/${listingId}`)
|
|---|
| 29 | const response = await fetch(url, {
|
|---|
| 30 | method: 'DELETE',
|
|---|
| 31 | headers: {
|
|---|
| 32 | 'Content-Type': 'application/json',
|
|---|
| 33 | 'X-User-Id': String(userId),
|
|---|
| 34 | },
|
|---|
| 35 | })
|
|---|
| 36 |
|
|---|
| 37 | if (!response.ok) {
|
|---|
| 38 | const error = await response.json()
|
|---|
| 39 | throw new Error(error.error || 'Failed to remove favorite')
|
|---|
| 40 | }
|
|---|
| 41 | }
|
|---|
| 42 |
|
|---|
| 43 | export async function getFavoritedListings(userId: number): Promise<any[]> {
|
|---|
| 44 | const url = joinUrl(getBaseUrl(), `/api/favorites`)
|
|---|
| 45 | const response = await fetch(url, {
|
|---|
| 46 | method: 'GET',
|
|---|
| 47 | headers: {
|
|---|
| 48 | 'Content-Type': 'application/json',
|
|---|
| 49 | 'X-User-Id': String(userId),
|
|---|
| 50 | },
|
|---|
| 51 | })
|
|---|
| 52 |
|
|---|
| 53 | if (!response.ok) {
|
|---|
| 54 | throw new Error('Failed to fetch favorites')
|
|---|
| 55 | }
|
|---|
| 56 |
|
|---|
| 57 | return await response.json()
|
|---|
| 58 | }
|
|---|
| 59 |
|
|---|
| 60 | export async function isFavorited(userId: number, listingId: number): Promise<boolean> {
|
|---|
| 61 | const url = joinUrl(getBaseUrl(), `/api/favorites/${listingId}/is-favorited`)
|
|---|
| 62 | const response = await fetch(url, {
|
|---|
| 63 | method: 'GET',
|
|---|
| 64 | headers: {
|
|---|
| 65 | 'Content-Type': 'application/json',
|
|---|
| 66 | 'X-User-Id': String(userId),
|
|---|
| 67 | },
|
|---|
| 68 | })
|
|---|
| 69 |
|
|---|
| 70 | if (!response.ok) {
|
|---|
| 71 | return false
|
|---|
| 72 | }
|
|---|
| 73 |
|
|---|
| 74 | const data = await response.json()
|
|---|
| 75 | return data.isFavorited
|
|---|
| 76 | }
|
|---|