forked from angular-redux/platform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathepics.ts
65 lines (58 loc) · 1.87 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
62
63
64
65
import { Injectable } from '@angular/core';
import { Epic } from 'redux-observable';
import { of } from 'rxjs';
import { catchError, filter, map, startWith, switchMap } from 'rxjs/operators';
import { AppState } from '../../store/model';
import { Animal, AnimalError, 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 this.createLoadAnimalEpic(animalType);
}
private createLoadAnimalEpic(
animalType: AnimalType,
): Epic<
AnimalAPIAction<Animal[] | AnimalError>,
AnimalAPIAction<Animal[] | AnimalError>,
AppState
> {
return (action$, state$) =>
action$.ofType(AnimalAPIActions.LOAD_ANIMALS).pipe(
filter(action =>
actionIsForCorrectAnimalType(animalType)(action as AnimalAPIAction),
),
filter(() => animalsNotAlreadyFetched(animalType, state$.value)),
switchMap(() =>
this.service.getAll(animalType).pipe(
map(data => this.actions.loadSucceeded(animalType, data)),
catchError(response =>
of(
this.actions.loadFailed(animalType, {
status: '' + response.status,
}),
),
),
startWith(this.actions.loadStarted(animalType)),
),
),
);
}
}