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