barker/bookie/src/app/product/product.service.ts

91 lines
3.0 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 { Product } from '../core/product';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
};
const url = '/api/products';
const serviceName = 'ProductService';
@Injectable({ providedIn: 'root' })
export class ProductService {
constructor(private http: HttpClient, private log: ErrorLoggerService) {}
get(id: string | null): Observable<Product> {
const getUrl: string = id === null ? `${url}` : `${url}/${id}`;
return this.http
.get<Product>(getUrl)
.pipe(catchError(this.log.handleError(serviceName, `get id=${id}`))) as Observable<Product>;
}
list(): Observable<Product[]> {
return this.http
.get<Product[]>(`${url}/list`)
.pipe(catchError(this.log.handleError(serviceName, 'list'))) as Observable<Product[]>;
}
listOfSaleCategory(id: string): Observable<Product[]> {
const options = { params: new HttpParams().set('sc', id) };
return this.http
.get<Product[]>(`${url}/query`, options)
.pipe(catchError(this.log.handleError(serviceName, 'listOfSaleCategory'))) as Observable<
Product[]
>;
}
listIsActiveOfCategory(id: string): Observable<Product[]> {
const options = { params: new HttpParams().set('mc', id) };
return this.http
.get<Product[]>(`${url}/query`, options)
.pipe(catchError(this.log.handleError(serviceName, 'listIsActiveOfCategory'))) as Observable<
Product[]
>;
}
save(product: Product): Observable<Product> {
return this.http
.post<Product>(`${url}`, product, httpOptions)
.pipe(catchError(this.log.handleError(serviceName, 'save'))) as Observable<Product>;
}
update(product: Product): Observable<Product> {
return this.http
.put<Product>(`${url}/${product.id}`, product, httpOptions)
.pipe(catchError(this.log.handleError(serviceName, 'update'))) as Observable<Product>;
}
updateSortOrder(list: Product[]): Observable<Product[]> {
return this.http
.post<Product[]>(`${url}/list`, list, httpOptions)
.pipe(catchError(this.log.handleError(serviceName, 'updateSortOrder'))) as Observable<
Product[]
>;
}
saveOrUpdate(product: Product): Observable<Product> {
if (!product.id) {
return this.save(product);
}
return this.update(product);
}
delete(id: string): Observable<Product> {
return this.http
.delete<Product>(`${url}/${id}`, httpOptions)
.pipe(catchError(this.log.handleError(serviceName, 'delete'))) as Observable<Product>;
}
balance(id: string, date: string): Observable<number> {
const options = { params: new HttpParams().set('d', date) };
return this.http
.get<number>(`${url}/balance`, options)
.pipe(catchError(this.log.handleError(serviceName, 'balance'))) as Observable<number>;
}
}