|
| 1 | +import { Reducer } from "redux"; |
| 2 | +import actionCreatorFactory, { isType } from "typescript-fsa"; |
| 3 | +import { ISagaModule } from "redux-dynamic-modules-saga"; |
| 4 | +import { SagaIterator } from "redux-saga"; |
| 5 | +import { takeLatest, put, delay, select } from "redux-saga/effects"; |
| 6 | +import { AuthModuleOwnState, getAuthModule } from "../auth"; |
| 7 | +import { IModule } from "redux-dynamic-modules"; |
| 8 | + |
| 9 | +interface BossInfo { |
| 10 | + id: string; |
| 11 | + name: string; |
| 12 | + title: string; |
| 13 | +} |
| 14 | + |
| 15 | +const actionCreator = actionCreatorFactory("BOSS"); |
| 16 | + |
| 17 | +const fetchBossInfo = actionCreator.async<{ token: string | null }, BossInfo>( |
| 18 | + "FETCH_BOSS_INFO" |
| 19 | +); |
| 20 | + |
| 21 | +export const fetchBossInfoOperation = actionCreator( |
| 22 | + "FETCH_BOSS_INFO_OPERATION" |
| 23 | +); |
| 24 | + |
| 25 | +type BossInfoState = BossInfo | null; |
| 26 | + |
| 27 | +const bossInfoReducer: Reducer<BossInfoState> = (state = null, action) => { |
| 28 | + if (isType(action, fetchBossInfo.done)) { |
| 29 | + return action.payload.result; |
| 30 | + } |
| 31 | + return state; |
| 32 | +}; |
| 33 | + |
| 34 | +export interface BossModuleOwnState { |
| 35 | + bossInfo: BossInfoState; |
| 36 | +} |
| 37 | + |
| 38 | +type GlobalState = BossModuleOwnState & AuthModuleOwnState; |
| 39 | + |
| 40 | +function* fetchBossInfoSaga(): SagaIterator { |
| 41 | + const token: string | null = yield select( |
| 42 | + (state: GlobalState) => state.authInfo && state.authInfo.token |
| 43 | + ); |
| 44 | + |
| 45 | + const params = { token }; |
| 46 | + yield put(fetchBossInfo.started(params)); |
| 47 | + |
| 48 | + yield delay(500); |
| 49 | + |
| 50 | + if (!token) { |
| 51 | + yield put(fetchBossInfo.failed({ params, error: "Invalid Token" })); |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + const result = { |
| 56 | + id: "bob@example.com", |
| 57 | + name: "Bob", |
| 58 | + title: "VPoE" |
| 59 | + }; // mock |
| 60 | + yield put(fetchBossInfo.done({ params, result })); |
| 61 | +} |
| 62 | + |
| 63 | +function* rootSaga(): SagaIterator { |
| 64 | + yield takeLatest(fetchBossInfoOperation, fetchBossInfoSaga); |
| 65 | +} |
| 66 | + |
| 67 | +function getBossModuleInternal(): ISagaModule<BossModuleOwnState> { |
| 68 | + return { |
| 69 | + id: "boss", |
| 70 | + reducerMap: { |
| 71 | + bossInfo: bossInfoReducer |
| 72 | + }, |
| 73 | + initialActions: [fetchBossInfoOperation()], |
| 74 | + sagas: [rootSaga] |
| 75 | + }; |
| 76 | +} |
| 77 | + |
| 78 | +export function getBossModule(): IModule<unknown>[] { |
| 79 | + // "boss" module depends on "auth" module |
| 80 | + return [getAuthModule(), getBossModuleInternal()]; |
| 81 | +} |
0 commit comments