import { HttpClient, 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'; import { ProductSku } from '../core/product-sku'; 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, 'getList'))) as Observable; } save(product: Product): Observable { return this.http .post(`${url}`, product) .pipe(catchError(this.log.handleError(serviceName, 'save'))) as Observable; } update(product: Product): Observable { return this.http .put(`${url}/${product.id}`, product) .pipe(catchError(this.log.handleError(serviceName, 'update'))) as Observable; } saveOrUpdate(product: Product): Observable { if (!product.id) { return this.save(product); } return this.update(product); } delete(id: string): Observable { return this.http .delete(`${url}/${id}`) .pipe(catchError(this.log.handleError(serviceName, 'delete'))) as Observable; } autocompleteProduct(query: string, isPurchased: boolean | null): Observable { const options = { params: new HttpParams().set('q', query), }; if (isPurchased !== null) { options.params = options.params.set('p', isPurchased.toString()); } return this.http .get(`${url}/q-product`, options) .pipe(catchError(this.log.handleError(serviceName, 'autocomplete'))) as Observable; } autocompleteSku( query: string, isPurchased: boolean | null, date?: string, vendorId?: string, ): Observable { const options = { params: new HttpParams().set('q', query), }; if (isPurchased !== null) { options.params = options.params.set('p', isPurchased.toString()); } if (!!vendorId && !!date) { options.params = options.params.set('v', vendorId as string).set('d', date as string); } return this.http .get(`${url}/q-sku`, options) .pipe(catchError(this.log.handleError(serviceName, 'autocomplete'))) as Observable; } }