forked from weavedev/redux-lazy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReduxLazy.ts
91 lines (76 loc) · 2.43 KB
/
ReduxLazy.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { SagaIterator } from '@redux-saga/types';
import { ActionMap, ActionTypesFromActionMap, InternalReducer, Reduxable } from '@weavedev/reduxable';
import { Action } from 'redux';
import { put } from 'redux-saga/effects';
interface SaveAction<T, D> extends Action<T> {
data: D;
}
interface ReduxLazyActionMap<T, D> extends ActionMap {
save: SaveAction<T, D>;
}
interface LazyState<D> {
data: D;
updated: {
data: string;
};
}
/**
* With love for Thijs
*/
export class ReduxLazy<T extends string, D> extends Reduxable<LazyState<D>, ReduxLazyActionMap<T, D>, [D]> {
public readonly actionTypeMap: ActionTypesFromActionMap<ReduxLazyActionMap<T, D>>;
public readonly defaultStateData: D;
constructor(save: T, defaultState: D) {
super();
this.actionTypeMap = {
save,
};
this.defaultStateData = defaultState;
}
public get actionMap(): ReduxLazyActionMap<T, D> {
throw new Error('ReduxAsync.actions should only be used as a TypeScript type provider');
}
public get defaultState(): LazyState<D> {
return {
data: this.defaultStateData,
updated: {
data: new Date().toISOString(),
},
};
}
public get internalReducer(): InternalReducer<LazyState<D>> {
const context: ReduxLazy<T, D> = this;
return (s: LazyState<D>, action: Action): LazyState<D> => {
switch(action.type) {
case (context.actionTypeMap.save):
return {
...s,
data: (<SaveAction<T, D>>action).data,
updated: {
data: new Date().toISOString(),
},
};
default:
return s;
}
};
}
public get saga(): (() => Iterator<never>) {
return function* (): Iterator<never> {/* Stub */};
}
public run(i: D): SaveAction<T, D> {
return {
type: this.actionTypeMap.save,
data: i,
};
}
public get runSaga(): (i: D) => SagaIterator<LazyState<D>> {
const context: ReduxLazy<T, D> = this;
return function* (i: D): SagaIterator<LazyState<D>> {
// Fire request
yield put(context.run(i));
// Simulate the next store state
return context.state;
};
}
}