source: petify-frontend/src/api/favorites.ts@ fa32d0f

Last change on this file since fa32d0f was 92e7c7a, checked in by veronika-ils <ilioskaveronika@…>, 11 hours ago

Petify fullstack project

  • Property mode set to 100644
File size: 2.0 KB
Line 
1function getBaseUrl(): string {
2 const base = (import.meta.env.VITE_API_BASE_URL as string | undefined) ?? ''
3 return base.replace(/\/$/, '')
4}
5
6function joinUrl(base: string, path: string): string {
7 if (!base) return path
8 return `${base}${path.startsWith('/') ? '' : '/'}${path}`
9}
10
11export 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
27export 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
43export 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
60export 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}
Note: See TracBrowser for help on using the repository browser.