barker/bookie/src/app/guest-book/guest-book.service.ts

62 lines
2.1 KiB
TypeScript

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/internal/Observable';
import { catchError } from 'rxjs/operators';
import { ErrorLoggerService } from '../core/error-logger.service';
import { GuestBook } from './guest-book';
import { GuestBookList } from './guest-book-list';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
};
const url = '/api/guest-book';
const customerUrl = '/api/customers';
const serviceName = 'GuestBookService';
@Injectable({ providedIn: 'root' })
export class GuestBookService {
constructor(private http: HttpClient, private log: ErrorLoggerService) {}
get(id: string | null): Observable<GuestBook> {
const getUrl: string = id === null ? url : `${url}/${id}`;
return this.http
.get<GuestBook>(getUrl)
.pipe(catchError(this.log.handleError(serviceName, `get id=${id}`))) as Observable<GuestBook>;
}
list(date: string | null): Observable<GuestBookList> {
const options = { params: new HttpParams().set('q', date === null ? '' : date) };
return this.http
.get<GuestBookList>(`${url}/list`, options)
.pipe(catchError(this.log.handleError(serviceName, 'list'))) as Observable<GuestBookList>;
}
save(guestBook: GuestBook): Observable<GuestBook> {
return this.http
.post<GuestBook>(url, guestBook, httpOptions)
.pipe(catchError(this.log.handleError(serviceName, 'save'))) as Observable<GuestBook>;
}
update(guestBook: GuestBook): Observable<GuestBook> {
return this.http
.put<GuestBook>(`${url}/${guestBook.id}`, guestBook, httpOptions)
.pipe(catchError(this.log.handleError(serviceName, 'update'))) as Observable<GuestBook>;
}
saveOrUpdate(guestBook: GuestBook): Observable<GuestBook> {
if (!guestBook.id) {
return this.save(guestBook);
}
return this.update(guestBook);
}
delete(id: string): Observable<GuestBook> {
return this.http
.delete<GuestBook>(`${url}/${id}`, httpOptions)
.pipe(catchError(this.log.handleError(serviceName, 'delete'))) as Observable<GuestBook>;
}
}