-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplaces.service.ts
91 lines (78 loc) · 2.52 KB
/
places.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/* eslint-disable @typescript-eslint/no-unused-vars */
import { inject, Injectable, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';
import { throwError } from 'rxjs';
import { Place } from '../models/place.model';
import { ErrorService } from './error.service';
@Injectable({
providedIn: 'root',
})
export class PlacesService {
private userPlaces = signal<Place[]>([]);
loadedUserPlaces = this.userPlaces.asReadonly();
private http = inject(HttpClient);
private errorServ = inject(ErrorService);
loadAvailablePlaces() {
return this.fetchPlaces('/api/v2/places', 'Error loading available places!');
}
loadUserPlaces() {
return this.fetchPlaces('/api/v2/user-places', 'Error loading user places!').pipe(
tap({
next: resp => {
if (resp) {
this.userPlaces.set(resp.places);
}
},
}),
);
}
addPlaceToUserPlaces(place: Place) {
const prevPlaces = this.userPlaces();
if (!prevPlaces.some(p => p.id === place.id)) {
// optimistic update
this.userPlaces.set([...prevPlaces, place]);
}
return this.http
.put('/api/v2/user-places', {
placeId: place.id,
})
.pipe(
catchError(err => {
this.userPlaces.set(prevPlaces);
this.errorServ.showError('Unable to store the selected place!');
return throwError(() => new Error('Unable to store the selected place!'));
}),
);
}
removeUserPlace(place: Place) {
const prevPlaces = this.userPlaces();
if (prevPlaces.some(p => p.id === place.id)) {
// optimistic update
this.userPlaces.set(prevPlaces.filter(pl => pl.id !== place.id));
}
return this.http.delete('/api/v2/user-places/' + place.id).pipe(
catchError(err => {
this.userPlaces.set(prevPlaces);
this.errorServ.showError('Unable to remove the selected place!');
return throwError(() => new Error('Unable to remove the selected place!'));
}),
);
}
private fetchPlaces(url: string, errMsg: string) {
return this.http
.get<{ places: Place[] }>(url, {
observe: 'response', // it'll give full response including status code
})
.pipe(
tap(rawResp => {
console.log('Raw Response: ', rawResp);
}),
map(data => data.body),
catchError(error => {
console.error(error);
return throwError(() => new Error(errMsg));
}),
);
}
}