Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / packages / mail / forwarding / incoming.ts
blob774a02eaa96d8eb94fe87d498b83514110e2307e
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 { queryAllIncomingForwardings } from '@proton/shared/lib/api/forwardings';
7 import updateCollection from '@proton/shared/lib/helpers/updateCollection';
8 import type { IncomingAddressForwarding } from '@proton/shared/lib/interfaces';
10 interface State {
11     incomingAddressForwarding: ModelState<IncomingAddressForwarding[]>;
14 const name = 'incomingAddressForwarding';
15 type SliceState = State[typeof name];
16 type Model = NonNullable<SliceState['value']>;
18 export const selectIncomingForwarding = (state: State) => state[name];
20 const modelThunk = createAsyncModelThunk<Model, State, ProtonThunkArguments>(`${name}/fetch`, {
21     miss: ({ extraArgument }) => {
22         return queryAllIncomingForwardings(extraArgument.api);
23     },
24     previous: previousSelector(selectIncomingForwarding),
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.IncomingAddressForwardings) {
36                 state.value = updateCollection({
37                     model: state.value,
38                     events: action.payload.IncomingAddressForwardings,
39                     itemKey: 'IncomingAddressForwarding',
40                 });
41             }
42         });
43     },
44 });
46 export const incomingAddressForwardingsReducer = { [name]: slice.reducer };
47 export const incomingAddressForwardingsThunk = modelThunk.thunk;