Merge branch 'renovate/all-minor-patch' into 'main'
[ProtonMail-WebClient.git] / packages / calendar / calendarUserSettings / index.ts
blob5273c55c7921bc0382306685fdb65fe5ae763bf1
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 { getCalendarUserSettings } from '@proton/shared/lib/api/calendars';
7 import updateObject from '@proton/shared/lib/helpers/updateObject';
8 import type { CalendarUserSettings } from '@proton/shared/lib/interfaces/calendar';
10 interface State {
11     calendarUserSettings: ModelState<CalendarUserSettings>;
14 const name = 'calendarUserSettings' as const;
15 type SliceState = State[typeof name];
16 type Model = NonNullable<SliceState['value']>;
18 export const selectCalendarUserSettings = (state: State) => state[name];
20 const modelThunk = createAsyncModelThunk<Model, State, ProtonThunkArguments>(`${name}/fetch`, {
21     miss: ({ extraArgument }) => {
22         return extraArgument
23             .api<{ CalendarUserSettings: CalendarUserSettings }>(getCalendarUserSettings())
24             .then(({ CalendarUserSettings }) => {
25                 return CalendarUserSettings;
26             });
27     },
28     previous: previousSelector(selectCalendarUserSettings),
29 });
31 const initialState = getInitialModelState<Model>();
32 const slice = createSlice({
33     name,
34     initialState,
35     reducers: {},
36     extraReducers: (builder) => {
37         handleAsyncModel(builder, modelThunk);
38         builder.addCase(serverEvent, (state, action) => {
39             if (state.value && action.payload.CalendarUserSettings) {
40                 state.value = updateObject(state.value, action.payload.CalendarUserSettings);
41             }
42         });
43     },
44 });
46 export const calendarSettingsReducer = { [name]: slice.reducer };
47 export const calendarSettingsThunk = modelThunk.thunk;