94 lines
2.7 KiB
TypeScript
94 lines
2.7 KiB
TypeScript
import {Injectable} from '@angular/core';
|
|
import {Decoration} from '../../models/model-interfaces';
|
|
import {RequestMethod, RequestOptions, URLSearchParams} from '@angular/http';
|
|
import {Observable} from 'rxjs/Observable';
|
|
import {ADD, EDIT, LOAD, REMOVE, Store} from '../stores/generic-store';
|
|
import {AppConfig} from '../../app.config';
|
|
import {HttpGateway} from '../http-gateway';
|
|
|
|
@Injectable()
|
|
export class DecorationService {
|
|
|
|
decorations$: Observable<Decoration[]>;
|
|
|
|
decorationStore = new Store<Decoration>();
|
|
|
|
constructor(private httpGateway: HttpGateway,
|
|
private config: AppConfig) {
|
|
this.decorations$ = this.decorationStore.items$;
|
|
}
|
|
|
|
findDecorations(query = '', fractionFilter?) {
|
|
const searchParams = new URLSearchParams();
|
|
searchParams.append('q', query);
|
|
if (fractionFilter) {
|
|
searchParams.append('fractFilter', fractionFilter);
|
|
}
|
|
|
|
this.httpGateway.get(this.config.apiDecorationPath, searchParams)
|
|
.map(res => res.json())
|
|
.do((squads) => {
|
|
this.decorationStore.dispatch({type: LOAD, data: squads});
|
|
}).subscribe(_ => {
|
|
});
|
|
|
|
return this.decorations$;
|
|
}
|
|
|
|
getDecoration(id: number | string): Observable<Decoration> {
|
|
return this.httpGateway.get(this.config.apiDecorationPath + id)
|
|
.map(res => res.json());
|
|
}
|
|
|
|
/**
|
|
* For creating new data with POST or
|
|
* update existing with patch PATCH
|
|
*/
|
|
submitDecoration(decoration: Decoration, imageFile?) {
|
|
let requestUrl = this.config.apiDecorationPath;
|
|
let requestMethod: RequestMethod;
|
|
let accessType;
|
|
let body;
|
|
|
|
if (decoration._id) {
|
|
requestUrl += decoration._id;
|
|
requestMethod = RequestMethod.Patch;
|
|
accessType = EDIT;
|
|
} else {
|
|
requestMethod = 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;
|
|
}
|
|
|
|
const options = new RequestOptions({
|
|
body: body,
|
|
method: requestMethod,
|
|
});
|
|
|
|
return this.httpGateway.request(requestUrl, options)
|
|
.map(res => res.json())
|
|
.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});
|
|
});
|
|
}
|
|
}
|