import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; 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 { const getUrl: string = id === null ? `${url}` : `${url}/${id}`; return this.http .get(getUrl) .pipe(catchError(this.log.handleError(serviceName, `get id=${id}`))) as Observable; } list(): Observable { return this.http .get(`${url}/list`) .pipe(catchError(this.log.handleError(serviceName, 'list'))) as Observable; } listOfSaleCategory(id: string): Observable { const options = { params: new HttpParams().set('sc', id) }; return this.http .get(`${url}/query`, options) .pipe(catchError(this.log.handleError(serviceName, 'listOfSaleCategory'))) as Observable; } listIsActiveOfCategory(id: string): Observable { const options = { params: new HttpParams().set('mc', id) }; return this.http .get(`${url}/query`, options) .pipe(catchError(this.log.handleError(serviceName, 'listIsActiveOfCategory'))) as Observable; } save(product: Product): Observable { return this.http .post(`${url}`, product, httpOptions) .pipe(catchError(this.log.handleError(serviceName, 'save'))) as Observable; } update(product: Product): Observable { return this.http .put(`${url}/${product.id}`, product, httpOptions) .pipe(catchError(this.log.handleError(serviceName, 'update'))) as Observable; } updateSortOrder(list: Product[]): Observable { return this.http .post(`${url}/list`, list, httpOptions) .pipe(catchError(this.log.handleError(serviceName, 'updateSortOrder'))) as Observable; } saveOrUpdate(product: Product): Observable { if (!product.versionId) { return this.save(product); } return this.update(product); } delete(id: string): Observable { return this.http .delete(`${url}/${id}`, httpOptions) .pipe(catchError(this.log.handleError(serviceName, 'delete'))) as Observable; } balance(id: string, date: string): Observable { const options = { params: new HttpParams().set('d', date) }; return this.http .get(`${url}/balance`, options) .pipe(catchError(this.log.handleError(serviceName, 'balance'))) as Observable; } }