Refactor getOrganizationSettings with requestActionsFactory
[ProtonMail-WebClient.git] / packages / pass / store / sagas / client / sync.saga.ts
blob8ab68cfcde9a316f3940838088164868494acf30
1 import { call, put, race, select, take } from 'redux-saga/effects';
3 import {
4     getUserAccessIntent,
5     getUserFeaturesIntent,
6     secureLinksGet,
7     startEventPolling,
8     stateDestroy,
9     stopEventPolling,
10     syncFailure,
11     syncIntent,
12     syncSuccess,
13 } from '@proton/pass/store/actions';
14 import { getOrganizationSettings } from '@proton/pass/store/actions/creators/organization';
15 import { withRevalidate } from '@proton/pass/store/request/enhancers';
16 import { synchronize } from '@proton/pass/store/sagas/client/sync';
17 import { selectUser } from '@proton/pass/store/selectors';
18 import type { State } from '@proton/pass/store/types';
19 import { wait } from '@proton/shared/lib/helpers/promise';
21 function* syncWorker({ payload }: ReturnType<typeof syncIntent>) {
22     yield put(stopEventPolling());
24     const state = (yield select()) as State;
25     const user = selectUser(state);
27     if (!user) return;
29     try {
30         yield wait(1500);
32         yield put(withRevalidate(getUserAccessIntent(user.ID)));
33         yield put(withRevalidate(getUserFeaturesIntent(user.ID)));
34         yield put(withRevalidate(getOrganizationSettings.intent()));
35         yield put(withRevalidate(secureLinksGet.intent()));
37         yield put(syncSuccess(yield call(synchronize, payload.type)));
38     } catch (e: unknown) {
39         yield put(syncFailure(e));
40     } finally {
41         yield put(startEventPolling());
42     }
45 /* The `syncWorker` function can take a long time to complete. In order to avoid conflicts
46  * with any state resetting actions, we race the `sync` against such actions. */
47 export default function* watcher(): Generator {
48     while (true) {
49         yield call(function* () {
50             const action: ReturnType<typeof syncIntent> = yield take(syncIntent.match);
51             yield race({
52                 sync: syncWorker(action),
53                 cancel: take(stateDestroy.match),
54             });
55         });
56     }