-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathepics.ts
61 lines (55 loc) · 1.83 KB
/
epics.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { Injectable } from '@angular/core';
import { createEpicMiddleware, Epic } from 'redux-observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/startWith';
import { of } from 'rxjs/observable/of';
import { AppState } from '../../store/model';
import { AnimalType } from '../model';
import { AnimalAPIAction, AnimalAPIActions } from './actions';
import { AnimalAPIService } from './service';
const animalsNotAlreadyFetched = (
animalType: AnimalType,
state: AppState,
): boolean =>
!(
state[animalType] &&
state[animalType].items &&
Object.keys(state[animalType].items).length
);
const actionIsForCorrectAnimalType = (animalType: AnimalType) => (
action: AnimalAPIAction,
): boolean => action.meta.animalType === animalType;
@Injectable()
export class AnimalAPIEpics {
constructor(
private service: AnimalAPIService,
private actions: AnimalAPIActions,
) {}
createEpic(animalType: AnimalType) {
return createEpicMiddleware(this.createLoadAnimalEpic(animalType));
}
private createLoadAnimalEpic(
animalType: AnimalType,
): Epic<AnimalAPIAction, AppState> {
return (action$, store) =>
action$
.ofType(AnimalAPIActions.LOAD_ANIMALS)
.filter(action => actionIsForCorrectAnimalType(animalType)(action))
.filter(() => animalsNotAlreadyFetched(animalType, store.getState()))
.switchMap(() =>
this.service
.getAll(animalType)
.map(data => this.actions.loadSucceeded(animalType, data))
.catch(response =>
of(
this.actions.loadFailed(animalType, {
status: '' + response.status,
}),
),
)
.startWith(this.actions.loadStarted(animalType)),
);
}
}