import {Injectable} from '@angular/core'; import {Decoration} from '../../models/model-interfaces'; import {Observable} from 'rxjs/Observable'; import {ADD, EDIT, LOAD, REMOVE, Store} from '../stores/generic-store'; import {AppConfig} from '../../app.config'; import {HttpGateway, HttpMethod} from '../http-gateway'; import {HttpParams} from '@angular/common/http'; @Injectable() export class DecorationService { decorations$: Observable; decorationStore = new Store(); constructor(private httpGateway: HttpGateway, private config: AppConfig) { this.decorations$ = this.decorationStore.items$; } findDecorations(query = '', fractionFilter?): Observable { let searchParams = new HttpParams().append('q', query); if (fractionFilter) { searchParams = searchParams.append('fractFilter', fractionFilter); } this.httpGateway.get(this.config.apiDecorationPath, searchParams) .do((squads) => { this.decorationStore.dispatch({type: LOAD, data: squads}); }).subscribe(_ => { }); return this.decorations$; } getDecoration(id: number | string): Observable { return this.httpGateway.get(this.config.apiDecorationPath + id); } /** * For creating new data with POST or * update existing with patch PATCH */ submitDecoration(decoration: Decoration, imageFile?) { let requestUrl = this.config.apiDecorationPath; let requestMethod: HttpMethod; let accessType; let body; if (decoration._id) { requestUrl += decoration._id; requestMethod = 'PATCH'; accessType = EDIT; } else { requestMethod = 'POST'; accessType = ADD; } if (imageFile) { body = new FormData(); Object.keys(decoration).map((objectKey) => { if (decoration[objectKey] !== undefined) { body.append(objectKey, decoration[objectKey]); } }); body.append('image', imageFile, imageFile.name); } else { body = decoration; } return this.httpGateway.request(requestUrl, body, requestMethod) .do(savedDecoration => { const action = {type: accessType, data: savedDecoration}; this.decorationStore.dispatch(action); }); } deleteDecoration(decoration: Decoration) { return this.httpGateway.delete(this.config.apiDecorationPath + decoration._id) .do(res => { this.decorationStore.dispatch({type: REMOVE, data: decoration}); }); } }