shlink-web-client/src/visits/reducers/visitsOverview.ts

54 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-02-18 12:40:37 +03:00
import type { PayloadAction } from '@reduxjs/toolkit';
import { createSlice } from '@reduxjs/toolkit';
import type { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
2023-02-18 13:11:01 +03:00
import type { ShlinkVisitsOverview } from '../../api/types';
2022-11-11 22:23:19 +03:00
import { createAsyncThunk } from '../../utils/helpers/redux';
import { groupNewVisitsByType } from '../types/helpers';
2022-11-11 22:23:19 +03:00
import { createNewVisits } from './visitCreation';
2022-11-11 22:23:19 +03:00
const REDUCER_PREFIX = 'shlink/visitsOverview';
export interface VisitsOverview {
visitsCount: number;
orphanVisitsCount: number;
loading: boolean;
error: boolean;
}
2022-11-11 22:23:19 +03:00
export type GetVisitsOverviewAction = PayloadAction<ShlinkVisitsOverview>;
const initialState: VisitsOverview = {
visitsCount: 0,
orphanVisitsCount: 0,
loading: false,
error: false,
};
2022-11-11 22:23:19 +03:00
export const loadVisitsOverview = (buildShlinkApiClient: ShlinkApiClientBuilder) => createAsyncThunk(
`${REDUCER_PREFIX}/loadVisitsOverview`,
(_: void, { getState }): Promise<ShlinkVisitsOverview> => buildShlinkApiClient(getState).getVisitsOverview(),
);
export const visitsOverviewReducerCreator = (
loadVisitsOverviewThunk: ReturnType<typeof loadVisitsOverview>,
) => createSlice({
name: REDUCER_PREFIX,
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(loadVisitsOverviewThunk.pending, () => ({ ...initialState, loading: true }));
builder.addCase(loadVisitsOverviewThunk.rejected, () => ({ ...initialState, error: true }));
builder.addCase(loadVisitsOverviewThunk.fulfilled, (_, { payload }) => ({ ...initialState, ...payload }));
builder.addCase(createNewVisits, ({ visitsCount, orphanVisitsCount = 0, ...rest }, { payload }) => {
const { createdVisits } = payload;
const { regularVisits, orphanVisits } = groupNewVisitsByType(createdVisits);
return {
...rest,
visitsCount: visitsCount + regularVisits.length,
orphanVisitsCount: orphanVisitsCount + orphanVisits.length,
};
});
},
2022-11-11 22:23:19 +03:00
});