89 lines
2.7 KiB
TypeScript
89 lines
2.7 KiB
TypeScript
import {Injectable} from '@angular/core';
|
|
import {User} 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} from '../http-gateway';
|
|
import {HttpParams} from '@angular/common/http';
|
|
|
|
@Injectable()
|
|
export class UserService {
|
|
|
|
users$: Observable<User[]>;
|
|
|
|
userStore = new Store<User>();
|
|
|
|
totalCount = 0;
|
|
|
|
constructor(private httpGateway: HttpGateway,
|
|
private config: AppConfig) {
|
|
this.users$ = this.userStore.items$;
|
|
}
|
|
|
|
findUsers(filter, limit?, offset?, action = LOAD): Observable<User[]> {
|
|
let searchParams = new HttpParams();
|
|
if (limit) {
|
|
searchParams = searchParams.append('limit', limit);
|
|
}
|
|
if (offset) {
|
|
searchParams = searchParams.append('offset', offset);
|
|
}
|
|
if (filter) {
|
|
if (filter.query) {
|
|
searchParams = searchParams.append('q', filter.query);
|
|
}
|
|
if (filter.fraction) {
|
|
searchParams = searchParams.append('fractFilter', filter.fraction);
|
|
}
|
|
if (filter.squadId) {
|
|
searchParams = searchParams.append('squadId', filter.squadId);
|
|
}
|
|
if (filter.decorationId) {
|
|
searchParams = searchParams.append('decorationId', filter.decorationId);
|
|
}
|
|
}
|
|
|
|
this.httpGateway.get<Response>(this.config.apiUserPath, searchParams, true)
|
|
.do((res) => {
|
|
const headerCount = parseInt(res.headers.get('x-total-count'), 10);
|
|
if (headerCount) {
|
|
this.totalCount = headerCount;
|
|
}
|
|
})
|
|
.map(res => res.body)
|
|
.do((users) => {
|
|
this.userStore.dispatch({type: action, data: users});
|
|
}).subscribe(_ => {
|
|
});
|
|
|
|
return this.users$;
|
|
}
|
|
|
|
getUser(_id: number | string): Observable<User> {
|
|
return this.httpGateway.get<User>(this.config.apiUserPath + _id);
|
|
}
|
|
|
|
submitUser(user): Observable<User> {
|
|
return this.httpGateway.post<User>(this.config.apiUserPath, user)
|
|
.do(savedUser => {
|
|
const action = {type: ADD, data: savedUser};
|
|
this.userStore.dispatch(action);
|
|
});
|
|
}
|
|
|
|
updateUser(user): Observable<User> {
|
|
return this.httpGateway.put<User>(this.config.apiUserPath + user._id, user)
|
|
.do(savedUser => {
|
|
const action = {type: EDIT, data: savedUser};
|
|
this.userStore.dispatch(action);
|
|
});
|
|
}
|
|
|
|
deleteUser(user) {
|
|
return this.httpGateway.delete(this.config.apiUserPath + user._id)
|
|
.do(res => {
|
|
this.userStore.dispatch({type: REMOVE, data: user});
|
|
});
|
|
}
|
|
}
|