import {Injectable} from '@angular/core'; import {Campaign} from '../../models/model-interfaces'; import {AppConfig} from '../../app.config'; import {HttpClient} from '../http-client'; import {ADD, EDIT, LOAD, REMOVE, Store} from '../stores/generic-store'; import {Observable} from 'rxjs'; import {RequestMethod, RequestOptions} from '@angular/http'; @Injectable() export class CampaignService { campaigns$: Observable; campaignStore = new Store(); constructor(private http: HttpClient, private config: AppConfig) { this.campaigns$ = this.campaignStore.items$; } getAllCampaigns() { return this.http.get(this.config.apiCampaignPath) .map(res => res.json()); } getAllCampaignsWithWars() { return this.http.get(this.config.apiWarPath) .map(res => res.json()) .do((ranks) => this.campaignStore.dispatch({type: LOAD, data: ranks})) } getCampaign(id: string) { return this.http.get(this.config.apiCampaignPath + '/' + id) .map(res => res.json()); } submitCampaign(campaign: Campaign) { let requestUrl: string; let requestMethod: RequestMethod let accessType; if (campaign._id) { requestUrl = this.config.apiCampaignPath + '/' + campaign._id; requestMethod = RequestMethod.Patch; accessType = EDIT; } else { requestUrl = this.config.apiCampaignPath; requestMethod = RequestMethod.Post; accessType = ADD; } const options = new RequestOptions({ body: campaign, method: requestMethod }); return this.http.request(requestUrl, options) .map(res => res.json()) .do(savedCampaign => { const action = {type: accessType, data: savedCampaign}; this.campaignStore.dispatch(action); }); } deleteCampaign(campaign: Campaign) { return this.http.delete(this.config.apiCampaignPath + '/' + campaign._id) .do(res => this.campaignStore.dispatch({type: REMOVE, data: campaign})); } }