opt-cc/static/src/app/services/army-management/rank.service.ts

89 lines
2.5 KiB
TypeScript
Raw Normal View History

2018-03-07 11:56:50 +01:00
import {Injectable} from '@angular/core';
import {Rank} from '../../models/model-interfaces';
2018-03-07 11:56:50 +01:00
import {Observable} from 'rxjs/Observable';
import {ADD, EDIT, LOAD, REMOVE, Store} from '../stores/generic-store';
2018-03-07 11:56:50 +01:00
import {AppConfig} from '../../app.config';
import {HttpGateway, HttpMethod} from '../http-gateway';
import {HttpParams} from '@angular/common/http';
2017-05-10 11:04:06 +02:00
@Injectable()
export class RankService {
ranks$: Observable<Rank[]>;
rankStore = new Store<Rank>();
constructor(private httpGateway: HttpGateway,
2017-05-10 11:04:06 +02:00
private config: AppConfig) {
this.ranks$ = this.rankStore.items$;
2017-05-10 11:04:06 +02:00
}
findRanks(query = '', fractionFilter?): Observable<Rank[]> {
let searchParams = new HttpParams().append('q', query);
2017-05-10 11:04:06 +02:00
if (fractionFilter) {
searchParams = searchParams.append('fractFilter', fractionFilter);
2017-05-10 11:04:06 +02:00
}
this.httpGateway.get<Rank[]>(this.config.apiRankPath, searchParams)
2018-02-26 09:04:27 +01:00
.do((ranks) => {
this.rankStore.dispatch({type: LOAD, data: ranks});
}).subscribe(_ => {
2017-05-10 11:04:06 +02:00
});
return this.ranks$;
}
getRank(id: number | string): Observable<Rank> {
return this.httpGateway.get<Rank>(this.config.apiRankPath + id);
2017-05-10 11:04:06 +02:00
}
2017-05-15 15:32:36 +02:00
/**
* For creating new data with POST or
* update existing with patch PATCH
*/
submitRank(rank: Rank, imageFile?): Observable<Rank> {
let requestUrl = this.config.apiRankPath;
let requestMethod: HttpMethod;
2017-05-15 15:32:36 +02:00
let accessType;
let body;
if (rank._id) {
requestUrl += rank._id;
requestMethod = 'PATCH';
2017-05-15 15:32:36 +02:00
accessType = EDIT;
} else {
requestMethod = 'POST';
2017-05-15 15:32:36 +02:00
accessType = ADD;
}
if (imageFile) {
body = new FormData();
Object.keys(rank).map((objectKey) => {
if (rank[objectKey] !== undefined) {
body.append(objectKey, rank[objectKey]);
}
});
body.append('image', imageFile, imageFile.name);
} else {
body = rank;
}
return this.httpGateway.request<Rank>(requestUrl, body, requestMethod)
2018-02-26 09:04:27 +01:00
.do(savedRank => {
const action = {type: accessType, data: savedRank};
// leave some time to save image file before accessing it through list view
2018-02-26 09:04:27 +01:00
setTimeout(() => {
this.rankStore.dispatch(action);
}, 300);
});
2017-05-15 15:32:36 +02:00
}
deleteRank(rank: Rank) {
return this.httpGateway.delete(this.config.apiRankPath + rank._id)
2018-02-26 09:04:27 +01:00
.do(res => {
this.rankStore.dispatch({type: REMOVE, data: rank});
});
}
2017-05-10 11:04:06 +02:00
}