Merge branch 'INDA-330-pii-update' into 'main'
[ProtonMail-WebClient.git] / packages / mail / importerConfig / index.ts
blob464172b8d6d4b32c00466480d15ae0623508dfa6
1 import { createSlice } from '@reduxjs/toolkit';
3 import { type ModelState, getInitialModelState, serverEvent } from '@proton/account';
4 import type { ProtonThunkArguments } from '@proton/redux-shared-store-types';
5 import { createAsyncModelThunk, handleAsyncModel, previousSelector } from '@proton/redux-utilities';
6 import { getApiEnvConfig } from '@proton/shared/lib/api/apiEnvironmentConfig';
7 import updateObject from '@proton/shared/lib/helpers/updateObject';
8 import type { ApiEnvironmentConfig } from '@proton/shared/lib/interfaces';
10 interface State {
11     importerConfig: ModelState<ApiEnvironmentConfig>;
14 const name = 'importerConfig' as const;
15 type SliceState = State[typeof name];
16 type Model = NonNullable<SliceState['value']>;
18 export const selectImporterConfig = (state: State) => state[name];
20 const modelThunk = createAsyncModelThunk<Model, State, ProtonThunkArguments>(`${name}/fetch`, {
21     miss: ({ extraArgument }) => {
22         return extraArgument.api<{ Config: ApiEnvironmentConfig }>(getApiEnvConfig()).then(({ Config }) => Config);
23     },
24     previous: previousSelector(selectImporterConfig),
25 });
27 const initialState = getInitialModelState<Model>();
28 const slice = createSlice({
29     name,
30     initialState,
31     reducers: {},
32     extraReducers: (builder) => {
33         handleAsyncModel(builder, modelThunk);
34         builder.addCase(serverEvent, (state, action) => {
35             if (state.value && action.payload.Config) {
36                 state.value = updateObject(state.value, action.payload.Config);
37             }
38         });
39     },
40 });
42 export const importerConfigReducer = { [name]: slice.reducer };
43 export const importConfigThunk = modelThunk.thunk;