Passed
Pull Request — main (#343)
by Alejandro
03:59
created

src/visits/reducers/visitsOverview.ts   A

Complexity

Total Complexity 1
Complexity/F 0

Size

Lines of Code 53
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 93.33%

Importance

Changes 0
Metric Value
wmc 1
eloc 44
mnd 1
bc 1
fnc 0
dl 0
loc 53
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
ccs 14
cts 15
cp 0.9333
rs 10
1
import { Action, Dispatch } from 'redux';
2
import { ShlinkVisitsOverview } from '../../utils/services/types';
3
import { ShlinkApiClientBuilder } from '../../utils/services/ShlinkApiClientBuilder';
4
import { GetState } from '../../container/types';
5
import { buildReducer } from '../../utils/helpers/redux';
6
import { CREATE_VISITS, CreateVisitsAction } from './visitCreation';
7
8
/* eslint-disable padding-line-between-statements */
9 1
export const GET_OVERVIEW_START = 'shlink/visitsOverview/GET_OVERVIEW_START';
10 1
export const GET_OVERVIEW_ERROR = 'shlink/visitsOverview/GET_OVERVIEW_ERROR';
11 1
export const GET_OVERVIEW = 'shlink/visitsOverview/GET_OVERVIEW';
12
/* eslint-enable padding-line-between-statements */
13
14
export interface VisitsOverview {
15
  visitsCount: number;
16
  loading: boolean;
17
  error: boolean;
18
}
19
20
export type GetVisitsOverviewAction = ShlinkVisitsOverview & Action<string>;
21
22 1
const initialState: VisitsOverview = {
23
  visitsCount: 0,
24
  loading: false,
25
  error: false,
26
};
27
28
export default buildReducer<VisitsOverview, GetVisitsOverviewAction & CreateVisitsAction>({
29 1
  [GET_OVERVIEW_START]: () => ({ ...initialState, loading: true }),
30 1
  [GET_OVERVIEW_ERROR]: () => ({ ...initialState, error: true }),
31 1
  [GET_OVERVIEW]: (_, { visitsCount }) => ({ ...initialState, visitsCount }),
32
  [CREATE_VISITS]: ({ visitsCount, ...rest }, { createdVisits }) => ({
33
    ...rest,
34
    visitsCount: visitsCount + createdVisits.length,
35
  }),
36
}, initialState);
37
38 2
export const loadVisitsOverview = (buildShlinkApiClient: ShlinkApiClientBuilder) => () => async (
39
  dispatch: Dispatch,
40
  getState: GetState,
41
) => {
42 2
  dispatch({ type: GET_OVERVIEW_START });
43
44 2
  try {
45 2
    const { getVisitsOverview } = buildShlinkApiClient(getState);
46 2
    const result = await getVisitsOverview();
47
48 1
    dispatch({ type: GET_OVERVIEW, ...result });
49
  } catch (e) {
50 1
    dispatch({ type: GET_OVERVIEW_ERROR });
51
  }
52
};
53