83 lines
2.4 KiB
TypeScript
83 lines
2.4 KiB
TypeScript
import {Injectable} from '@angular/core';
|
|
import {Squad} 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 SquadService {
|
|
|
|
squads$: Observable<Squad[]>;
|
|
|
|
squadStore = new Store<Squad>();
|
|
|
|
constructor(private httpGateway: HttpGateway,
|
|
private config: AppConfig) {
|
|
this.squads$ = this.squadStore.items$;
|
|
}
|
|
|
|
findSquads(query = '', fractionFilter = ''): Observable<Squad[]> {
|
|
const searchParams = new HttpParams().append('q', query)
|
|
.append('fractFilter', fractionFilter);
|
|
|
|
this.httpGateway.get(this.config.apiSquadPath, searchParams)
|
|
.do((squads) => {
|
|
this.squadStore.dispatch({type: LOAD, data: squads});
|
|
}).subscribe(_ => {
|
|
});
|
|
|
|
return this.squads$;
|
|
}
|
|
|
|
getSquad(id: number | string): Observable<Squad> {
|
|
return this.httpGateway.get<Squad>(this.config.apiSquadPath + id);
|
|
}
|
|
|
|
/**
|
|
* For creating new data with POST or
|
|
* update existing with patch PATCH
|
|
*/
|
|
submitSquad(squad: Squad, imageFile?): Observable<Squad> {
|
|
let requestUrl = this.config.apiSquadPath;
|
|
let requestMethod: HttpMethod;
|
|
let accessType;
|
|
let body;
|
|
|
|
if (squad._id) {
|
|
requestUrl += squad._id;
|
|
requestMethod = 'PATCH';
|
|
accessType = EDIT;
|
|
} else {
|
|
requestMethod = 'POST';
|
|
accessType = ADD;
|
|
}
|
|
|
|
if (imageFile) {
|
|
body = new FormData();
|
|
Object.keys(squad).map((objectKey) => {
|
|
if (squad[objectKey] !== undefined) {
|
|
body.append(objectKey, squad[objectKey]);
|
|
}
|
|
});
|
|
body.append('image', imageFile, imageFile.name);
|
|
} else {
|
|
body = squad;
|
|
}
|
|
|
|
return this.httpGateway.request<Squad>(requestUrl, body, requestMethod)
|
|
.do(savedSquad => {
|
|
const action = {type: accessType, data: savedSquad};
|
|
this.squadStore.dispatch(action);
|
|
});
|
|
}
|
|
|
|
deleteSquad(squad: Squad) {
|
|
return this.httpGateway.delete(this.config.apiSquadPath + squad._id)
|
|
.do(res => {
|
|
this.squadStore.dispatch({type: REMOVE, data: squad});
|
|
});
|
|
}
|
|
}
|