Extracted duplicated code on creating visits reducers to a common helper function

This commit is contained in:
Alejandro Celaya 2022-11-12 20:37:04 +01:00
parent dac69daf03
commit 4b2c3d2db7
12 changed files with 137 additions and 239 deletions

View file

@ -1,11 +1,13 @@
import { flatten, prop, range, splitEvery } from 'ramda'; import { flatten, prop, range, splitEvery } from 'ramda';
import { createAction } from '@reduxjs/toolkit'; import { createAction, createSlice } from '@reduxjs/toolkit';
import { ShlinkPaginator, ShlinkVisits, ShlinkVisitsParams } from '../../api/types'; import { ShlinkPaginator, ShlinkVisits, ShlinkVisitsParams } from '../../api/types';
import { Visit } from '../types'; import { CreateVisit, Visit } from '../types';
import { DateInterval, dateToMatchingInterval } from '../../utils/dates/types'; import { DateInterval, dateToMatchingInterval } from '../../utils/dates/types';
import { LoadVisits, VisitsLoaded } from './types'; import { LoadVisits, VisitsInfo, VisitsLoaded } from './types';
import { createAsyncThunk } from '../../utils/helpers/redux'; import { createAsyncThunk } from '../../utils/helpers/redux';
import { ShlinkState } from '../../container/types'; import { ShlinkState } from '../../container/types';
import { parseApiError } from '../../api/utils';
import { createNewVisits } from './visitCreation';
const ITEMS_PER_PAGE = 5000; const ITEMS_PER_PAGE = 5000;
const PARALLEL_REQUESTS_COUNT = 4; const PARALLEL_REQUESTS_COUNT = 4;
@ -18,20 +20,20 @@ type VisitsLoader = (page: number, itemsPerPage: number) => Promise<ShlinkVisits
type LastVisitLoader = () => Promise<Visit | undefined>; type LastVisitLoader = () => Promise<Visit | undefined>;
interface VisitsAsyncThunkOptions<T extends LoadVisits = LoadVisits, R extends VisitsLoaded = VisitsLoaded> { interface VisitsAsyncThunkOptions<T extends LoadVisits = LoadVisits, R extends VisitsLoaded = VisitsLoaded> {
actionsPrefix: string; name: string;
createLoaders: (params: T, getState: () => ShlinkState) => [VisitsLoader, LastVisitLoader]; createLoaders: (params: T, getState: () => ShlinkState) => [VisitsLoader, LastVisitLoader];
getExtraFulfilledPayload: (params: T) => Partial<R>; getExtraFulfilledPayload: (params: T) => Partial<R>;
shouldCancel: (getState: () => ShlinkState) => boolean; shouldCancel: (getState: () => ShlinkState) => boolean;
} }
export const createVisitsAsyncThunk = <T extends LoadVisits = LoadVisits, R extends VisitsLoaded = VisitsLoaded>( export const createVisitsAsyncThunk = <T extends LoadVisits = LoadVisits, R extends VisitsLoaded = VisitsLoaded>(
{ actionsPrefix, createLoaders, getExtraFulfilledPayload, shouldCancel }: VisitsAsyncThunkOptions<T, R>, { name, createLoaders, getExtraFulfilledPayload, shouldCancel }: VisitsAsyncThunkOptions<T, R>,
) => { ) => {
const progressChangedAction = createAction<number>(`${actionsPrefix}/progressChanged`); const progressChangedAction = createAction<number>(`${name}/progressChanged`);
const largeAction = createAction<void>(`${actionsPrefix}/large`); const largeAction = createAction<void>(`${name}/large`);
const fallbackToIntervalAction = createAction<DateInterval>(`${actionsPrefix}/fallbackToInterval`); const fallbackToIntervalAction = createAction<DateInterval>(`${name}/fallbackToInterval`);
const asyncThunk = createAsyncThunk(actionsPrefix, async (params: T, { getState, dispatch }): Promise<R> => { const asyncThunk = createAsyncThunk(name, async (params: T, { getState, dispatch }): Promise<R> => {
const [visitsLoader, lastVisitLoader] = createLoaders(params, getState); const [visitsLoader, lastVisitLoader] = createLoaders(params, getState);
const loadVisitsInParallel = async (pages: number[]): Promise<Visit[]> => const loadVisitsInParallel = async (pages: number[]): Promise<Visit[]> =>
@ -94,3 +96,49 @@ export const lastVisitLoaderForLoader = (
return async () => loader({ page: 1, itemsPerPage: 1 }).then(({ data }) => data[0]); return async () => loader({ page: 1, itemsPerPage: 1 }).then(({ data }) => data[0]);
}; };
export const createVisitsReducer = <State extends VisitsInfo, AT extends ReturnType<typeof createVisitsAsyncThunk>>(
name: string,
{
asyncThunk,
largeAction,
fallbackToIntervalAction,
progressChangedAction,
}: AT,
initialState: State,
filterCreatedVisits: (state: State, createdVisits: CreateVisit[]) => CreateVisit[],
) => {
const { reducer, actions } = createSlice({
name,
initialState,
reducers: {
cancelGetVisits: (state) => ({ ...state, cancelLoad: true }),
},
extraReducers: (builder) => {
builder.addCase(asyncThunk.pending, () => ({ ...initialState, loading: true }));
builder.addCase(asyncThunk.rejected, (_, { error }) => (
{ ...initialState, error: true, errorData: parseApiError(error) }
));
builder.addCase(asyncThunk.fulfilled, (state, { payload }) => (
{ ...state, ...payload, loading: false, loadingLarge: false, error: false }
));
builder.addCase(largeAction, (state) => ({ ...state, loadingLarge: true }));
builder.addCase(progressChangedAction, (state, { payload: progress }) => ({ ...state, progress }));
builder.addCase(fallbackToIntervalAction, (state, { payload: fallbackInterval }) => (
{ ...state, fallbackInterval }
));
builder.addCase(createNewVisits, (state, { payload }) => {
const { visits } = state;
// @ts-expect-error TODO Fix the state inferred type
const newVisits = filterCreatedVisits(state, payload.createdVisits).map(({ visit }) => visit);
return { ...state, visits: [...newVisits, ...visits] };
});
},
});
const { cancelGetVisits } = actions;
return { reducer, cancelGetVisits };
};

View file

@ -1,11 +1,8 @@
import { createSlice } from '@reduxjs/toolkit';
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder'; import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
import { isBetween } from '../../utils/helpers/date'; import { isBetween } from '../../utils/helpers/date';
import { createVisitsAsyncThunk, lastVisitLoaderForLoader } from './common'; import { createVisitsAsyncThunk, createVisitsReducer, lastVisitLoaderForLoader } from './common';
import { createNewVisits } from './visitCreation';
import { domainMatches } from '../../short-urls/helpers'; import { domainMatches } from '../../short-urls/helpers';
import { LoadVisits, VisitsInfo } from './types'; import { LoadVisits, VisitsInfo } from './types';
import { parseApiError } from '../../api/utils';
const REDUCER_PREFIX = 'shlink/domainVisits'; const REDUCER_PREFIX = 'shlink/domainVisits';
@ -30,7 +27,7 @@ const initialState: DomainVisits = {
}; };
export const getDomainVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => createVisitsAsyncThunk({ export const getDomainVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => createVisitsAsyncThunk({
actionsPrefix: `${REDUCER_PREFIX}/getDomainVisits`, name: `${REDUCER_PREFIX}/getDomainVisits`,
createLoaders: ({ domain, query = {}, doIntervalFallback = false }: LoadDomainVisits, getState) => { createLoaders: ({ domain, query = {}, doIntervalFallback = false }: LoadDomainVisits, getState) => {
const { getDomainVisits: getVisits } = buildShlinkApiClient(getState); const { getDomainVisits: getVisits } = buildShlinkApiClient(getState);
const visitsLoader = async (page: number, itemsPerPage: number) => getVisits( const visitsLoader = async (page: number, itemsPerPage: number) => getVisits(
@ -46,42 +43,17 @@ export const getDomainVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) =>
}); });
export const domainVisitsReducerCreator = ( export const domainVisitsReducerCreator = (
{ asyncThunk, largeAction, progressChangedAction, fallbackToIntervalAction }: ReturnType<typeof getDomainVisits>, getVisitsCreator: ReturnType<typeof getDomainVisits>,
) => { ) => createVisitsReducer(
const { reducer, actions } = createSlice({ REDUCER_PREFIX,
name: REDUCER_PREFIX, // @ts-expect-error TODO Fix type inference
initialState, getVisitsCreator,
reducers: { initialState,
cancelGetDomainVisits: (state) => ({ ...state, cancelLoad: true }), ({ domain, query = {} }, createdVisits) => {
}, const { startDate, endDate } = query;
extraReducers: (builder) => { return createdVisits.filter(
builder.addCase(asyncThunk.pending, () => ({ ...initialState, loading: true })); ({ shortUrl, visit }) =>
builder.addCase(asyncThunk.rejected, (_, { error }) => ( shortUrl && domainMatches(shortUrl, domain) && isBetween(visit.date, startDate, endDate),
{ ...initialState, error: true, errorData: parseApiError(error) } );
)); },
builder.addCase(asyncThunk.fulfilled, (state, { payload }) => ( );
{ ...state, ...payload, loading: false, loadingLarge: false, error: false }
));
builder.addCase(largeAction, (state) => ({ ...state, loadingLarge: true }));
builder.addCase(progressChangedAction, (state, { payload: progress }) => ({ ...state, progress }));
builder.addCase(fallbackToIntervalAction, (state, { payload: fallbackInterval }) => (
{ ...state, fallbackInterval }
));
builder.addCase(createNewVisits, (state, { payload }) => {
const { domain, visits, query = {} } = state;
const { startDate, endDate } = query;
const newVisits = payload.createdVisits
.filter(({ shortUrl, visit }) =>
shortUrl && domainMatches(shortUrl, domain) && isBetween(visit.date, startDate, endDate))
.map(({ visit }) => visit);
return { ...state, visits: [...newVisits, ...visits] };
});
},
});
const { cancelGetDomainVisits } = actions;
return { reducer, cancelGetDomainVisits };
};

View file

@ -1,10 +1,7 @@
import { createSlice } from '@reduxjs/toolkit';
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder'; import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
import { isBetween } from '../../utils/helpers/date'; import { isBetween } from '../../utils/helpers/date';
import { createVisitsAsyncThunk, lastVisitLoaderForLoader } from './common'; import { createVisitsAsyncThunk, createVisitsReducer, lastVisitLoaderForLoader } from './common';
import { createNewVisits } from './visitCreation';
import { VisitsInfo } from './types'; import { VisitsInfo } from './types';
import { parseApiError } from '../../api/utils';
const REDUCER_PREFIX = 'shlink/orphanVisits'; const REDUCER_PREFIX = 'shlink/orphanVisits';
@ -18,7 +15,7 @@ const initialState: VisitsInfo = {
}; };
export const getNonOrphanVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => createVisitsAsyncThunk({ export const getNonOrphanVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => createVisitsAsyncThunk({
actionsPrefix: `${REDUCER_PREFIX}/getNonOrphanVisits`, name: `${REDUCER_PREFIX}/getNonOrphanVisits`,
createLoaders: ({ query = {}, doIntervalFallback = false }, getState) => { createLoaders: ({ query = {}, doIntervalFallback = false }, getState) => {
const { getNonOrphanVisits: shlinkGetNonOrphanVisits } = buildShlinkApiClient(getState); const { getNonOrphanVisits: shlinkGetNonOrphanVisits } = buildShlinkApiClient(getState);
const visitsLoader = async (page: number, itemsPerPage: number) => const visitsLoader = async (page: number, itemsPerPage: number) =>
@ -32,41 +29,13 @@ export const getNonOrphanVisits = (buildShlinkApiClient: ShlinkApiClientBuilder)
}); });
export const nonOrphanVisitsReducerCreator = ( export const nonOrphanVisitsReducerCreator = (
{ asyncThunk, largeAction, progressChangedAction, fallbackToIntervalAction }: ReturnType<typeof getNonOrphanVisits>, getVisitsCreator: ReturnType<typeof getNonOrphanVisits>,
) => { ) => createVisitsReducer(
const { reducer, actions } = createSlice({ REDUCER_PREFIX,
name: REDUCER_PREFIX, getVisitsCreator,
initialState, initialState,
reducers: { ({ query = {} }, createdVisits) => {
cancelGetNonOrphanVisits: (state) => ({ ...state, cancelLoad: true }), const { startDate, endDate } = query;
}, return createdVisits.filter(({ visit }) => isBetween(visit.date, startDate, endDate));
extraReducers: (builder) => { },
builder.addCase(asyncThunk.pending, () => ({ ...initialState, loading: true })); );
builder.addCase(asyncThunk.rejected, (_, { error }) => (
{ ...initialState, error: true, errorData: parseApiError(error) }
));
builder.addCase(asyncThunk.fulfilled, (state, { payload }) => (
{ ...state, ...payload, loading: false, loadingLarge: false, error: false }
));
builder.addCase(largeAction, (state) => ({ ...state, loadingLarge: true }));
builder.addCase(progressChangedAction, (state, { payload: progress }) => ({ ...state, progress }));
builder.addCase(fallbackToIntervalAction, (state, { payload: fallbackInterval }) => (
{ ...state, fallbackInterval }
));
builder.addCase(createNewVisits, (state, { payload }) => {
const { visits, query = {} } = state;
const { startDate, endDate } = query;
const newVisits = payload.createdVisits
.filter(({ visit }) => isBetween(visit.date, startDate, endDate))
.map(({ visit }) => visit);
return { ...state, visits: [...newVisits, ...visits] };
});
},
});
const { cancelGetNonOrphanVisits } = actions;
return { reducer, cancelGetNonOrphanVisits };
};

View file

@ -1,12 +1,9 @@
import { createSlice } from '@reduxjs/toolkit';
import { OrphanVisit, OrphanVisitType } from '../types'; import { OrphanVisit, OrphanVisitType } from '../types';
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder'; import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
import { isOrphanVisit } from '../types/helpers'; import { isOrphanVisit } from '../types/helpers';
import { isBetween } from '../../utils/helpers/date'; import { isBetween } from '../../utils/helpers/date';
import { createVisitsAsyncThunk, lastVisitLoaderForLoader } from './common'; import { createVisitsAsyncThunk, createVisitsReducer, lastVisitLoaderForLoader } from './common';
import { createNewVisits, CreateVisitsAction } from './visitCreation';
import { LoadVisits, VisitsInfo } from './types'; import { LoadVisits, VisitsInfo } from './types';
import { parseApiError } from '../../api/utils';
const REDUCER_PREFIX = 'shlink/orphanVisits'; const REDUCER_PREFIX = 'shlink/orphanVisits';
@ -27,7 +24,7 @@ const matchesType = (visit: OrphanVisit, orphanVisitsType?: OrphanVisitType) =>
!orphanVisitsType || orphanVisitsType === visit.type; !orphanVisitsType || orphanVisitsType === visit.type;
export const getOrphanVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => createVisitsAsyncThunk({ export const getOrphanVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => createVisitsAsyncThunk({
actionsPrefix: `${REDUCER_PREFIX}/getOrphanVisits`, name: `${REDUCER_PREFIX}/getOrphanVisits`,
createLoaders: ({ orphanVisitsType, query = {}, doIntervalFallback = false }: LoadOrphanVisits, getState) => { createLoaders: ({ orphanVisitsType, query = {}, doIntervalFallback = false }: LoadOrphanVisits, getState) => {
const { getOrphanVisits: getVisits } = buildShlinkApiClient(getState); const { getOrphanVisits: getVisits } = buildShlinkApiClient(getState);
const visitsLoader = async (page: number, itemsPerPage: number) => getVisits({ ...query, page, itemsPerPage }) const visitsLoader = async (page: number, itemsPerPage: number) => getVisits({ ...query, page, itemsPerPage })
@ -45,41 +42,13 @@ export const getOrphanVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) =>
}); });
export const orphanVisitsReducerCreator = ( export const orphanVisitsReducerCreator = (
{ asyncThunk, largeAction, progressChangedAction, fallbackToIntervalAction }: ReturnType<typeof getOrphanVisits>, getVisitsCreator: ReturnType<typeof getOrphanVisits>,
) => { ) => createVisitsReducer(
const { reducer, actions } = createSlice({ REDUCER_PREFIX,
name: REDUCER_PREFIX, getVisitsCreator,
initialState, initialState,
reducers: { ({ query = {} }, createdVisits) => {
cancelGetOrphanVisits: (state) => ({ ...state, cancelLoad: true }), const { startDate, endDate } = query;
}, return createdVisits.filter(({ visit, shortUrl }) => !shortUrl && isBetween(visit.date, startDate, endDate));
extraReducers: (builder) => { },
builder.addCase(asyncThunk.pending, () => ({ ...initialState, loading: true })); );
builder.addCase(asyncThunk.rejected, (_, { error }) => (
{ ...initialState, error: true, errorData: parseApiError(error) }
));
builder.addCase(asyncThunk.fulfilled, (state, { payload }) => (
{ ...state, ...payload, loading: false, loadingLarge: false, error: false }
));
builder.addCase(largeAction, (state) => ({ ...state, loadingLarge: true }));
builder.addCase(progressChangedAction, (state, { payload: progress }) => ({ ...state, progress }));
builder.addCase(fallbackToIntervalAction, (state, { payload: fallbackInterval }) => (
{ ...state, fallbackInterval }
));
builder.addCase(createNewVisits, (state, { payload }: CreateVisitsAction) => {
const { visits, query = {} } = state;
const { startDate, endDate } = query;
const newVisits = payload.createdVisits
.filter(({ visit, shortUrl }) => !shortUrl && isBetween(visit.date, startDate, endDate))
.map(({ visit }) => visit);
return { ...state, visits: [...newVisits, ...visits] };
});
},
});
const { cancelGetOrphanVisits } = actions;
return { reducer, cancelGetOrphanVisits };
};

View file

@ -1,12 +1,9 @@
import { createSlice } from '@reduxjs/toolkit';
import { shortUrlMatches } from '../../short-urls/helpers'; import { shortUrlMatches } from '../../short-urls/helpers';
import { ShortUrlIdentifier } from '../../short-urls/data'; import { ShortUrlIdentifier } from '../../short-urls/data';
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder'; import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
import { isBetween } from '../../utils/helpers/date'; import { isBetween } from '../../utils/helpers/date';
import { createVisitsAsyncThunk, lastVisitLoaderForLoader } from './common'; import { createVisitsAsyncThunk, createVisitsReducer, lastVisitLoaderForLoader } from './common';
import { createNewVisits, CreateVisitsAction } from './visitCreation';
import { LoadVisits, VisitsInfo } from './types'; import { LoadVisits, VisitsInfo } from './types';
import { parseApiError } from '../../api/utils';
const REDUCER_PREFIX = 'shlink/shortUrlVisits'; const REDUCER_PREFIX = 'shlink/shortUrlVisits';
@ -28,7 +25,7 @@ const initialState: ShortUrlVisits = {
}; };
export const getShortUrlVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => createVisitsAsyncThunk({ export const getShortUrlVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => createVisitsAsyncThunk({
actionsPrefix: `${REDUCER_PREFIX}/getShortUrlVisits`, name: `${REDUCER_PREFIX}/getShortUrlVisits`,
createLoaders: ({ shortCode, query = {}, doIntervalFallback = false }: LoadShortUrlVisits, getState) => { createLoaders: ({ shortCode, query = {}, doIntervalFallback = false }: LoadShortUrlVisits, getState) => {
const { getShortUrlVisits: shlinkGetShortUrlVisits } = buildShlinkApiClient(getState); const { getShortUrlVisits: shlinkGetShortUrlVisits } = buildShlinkApiClient(getState);
const visitsLoader = async (page: number, itemsPerPage: number) => shlinkGetShortUrlVisits( const visitsLoader = async (page: number, itemsPerPage: number) => shlinkGetShortUrlVisits(
@ -49,44 +46,17 @@ export const getShortUrlVisits = (buildShlinkApiClient: ShlinkApiClientBuilder)
}); });
export const shortUrlVisitsReducerCreator = ( export const shortUrlVisitsReducerCreator = (
{ asyncThunk, largeAction, progressChangedAction, fallbackToIntervalAction }: ReturnType<typeof getShortUrlVisits>, getVisitsCreator: ReturnType<typeof getShortUrlVisits>,
) => { ) => createVisitsReducer(
const { reducer, actions } = createSlice({ REDUCER_PREFIX,
name: REDUCER_PREFIX, // @ts-expect-error TODO Fix type inference
initialState, getVisitsCreator,
reducers: { initialState,
cancelGetShortUrlVisits: (state) => ({ ...state, cancelLoad: true }), ({ shortCode, domain, query = {} }, createdVisits) => {
}, const { startDate, endDate } = query;
extraReducers: (builder) => { return createdVisits.filter(
builder.addCase(asyncThunk.pending, () => ({ ...initialState, loading: true })); ({ shortUrl, visit }) =>
builder.addCase(asyncThunk.rejected, (_, { error }) => ( shortUrl && shortUrlMatches(shortUrl, shortCode, domain) && isBetween(visit.date, startDate, endDate),
{ ...initialState, error: true, errorData: parseApiError(error) } );
)); },
builder.addCase(asyncThunk.fulfilled, (state, { payload }) => ( );
{ ...state, ...payload, loading: false, loadingLarge: false, error: false }
));
builder.addCase(largeAction, (state) => ({ ...state, loadingLarge: true }));
builder.addCase(progressChangedAction, (state, { payload: progress }) => ({ ...state, progress }));
builder.addCase(fallbackToIntervalAction, (state, { payload: fallbackInterval }) => (
{ ...state, fallbackInterval }
));
builder.addCase(createNewVisits, (state, { payload }: CreateVisitsAction) => {
const { shortCode, domain, visits, query = {} } = state;
const { startDate, endDate } = query;
const newVisits = payload.createdVisits
.filter(
({ shortUrl, visit }) =>
shortUrl && shortUrlMatches(shortUrl, shortCode, domain) && isBetween(visit.date, startDate, endDate),
)
.map(({ visit }) => visit);
return newVisits.length === 0 ? state : { ...state, visits: [...newVisits, ...visits] };
});
},
});
const { cancelGetShortUrlVisits } = actions;
return { reducer, cancelGetShortUrlVisits };
};

View file

@ -1,10 +1,7 @@
import { createSlice } from '@reduxjs/toolkit';
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder'; import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
import { isBetween } from '../../utils/helpers/date'; import { isBetween } from '../../utils/helpers/date';
import { createVisitsAsyncThunk, lastVisitLoaderForLoader } from './common'; import { createVisitsAsyncThunk, createVisitsReducer, lastVisitLoaderForLoader } from './common';
import { createNewVisits } from './visitCreation';
import { LoadVisits, VisitsInfo } from './types'; import { LoadVisits, VisitsInfo } from './types';
import { parseApiError } from '../../api/utils';
const REDUCER_PREFIX = 'shlink/tagVisits'; const REDUCER_PREFIX = 'shlink/tagVisits';
@ -27,7 +24,7 @@ const initialState: TagVisits = {
}; };
export const getTagVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => createVisitsAsyncThunk({ export const getTagVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => createVisitsAsyncThunk({
actionsPrefix: `${REDUCER_PREFIX}/getTagVisits`, name: `${REDUCER_PREFIX}/getTagVisits`,
createLoaders: ({ tag, query = {}, doIntervalFallback = false }: LoadTagVisits, getState) => { createLoaders: ({ tag, query = {}, doIntervalFallback = false }: LoadTagVisits, getState) => {
const { getTagVisits: getVisits } = buildShlinkApiClient(getState); const { getTagVisits: getVisits } = buildShlinkApiClient(getState);
const visitsLoader = async (page: number, itemsPerPage: number) => getVisits( const visitsLoader = async (page: number, itemsPerPage: number) => getVisits(
@ -42,42 +39,15 @@ export const getTagVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => cr
shouldCancel: (getState) => getState().tagVisits.cancelLoad, shouldCancel: (getState) => getState().tagVisits.cancelLoad,
}); });
export const tagVisitsReducerCreator = ( export const tagVisitsReducerCreator = (getTagVisitsCreator: ReturnType<typeof getTagVisits>) => createVisitsReducer(
{ asyncThunk, largeAction, progressChangedAction, fallbackToIntervalAction }: ReturnType<typeof getTagVisits>, REDUCER_PREFIX,
) => { // @ts-expect-error TODO Fix type inference
const { reducer, actions } = createSlice({ getTagVisitsCreator,
name: REDUCER_PREFIX, initialState,
initialState, ({ tag, query = {} }, createdVisits) => {
reducers: { const { startDate, endDate } = query;
cancelGetTagVisits: (state) => ({ ...state, cancelLoad: true }), return createdVisits.filter(
}, ({ shortUrl, visit }) => shortUrl?.tags.includes(tag) && isBetween(visit.date, startDate, endDate),
extraReducers: (builder) => { );
builder.addCase(asyncThunk.pending, () => ({ ...initialState, loading: true })); },
builder.addCase(asyncThunk.rejected, (_, { error }) => ( );
{ ...initialState, error: true, errorData: parseApiError(error) }
));
builder.addCase(asyncThunk.fulfilled, (state, { payload }) => (
{ ...state, ...payload, loading: false, loadingLarge: false, error: false }
));
builder.addCase(largeAction, (state) => ({ ...state, loadingLarge: true }));
builder.addCase(progressChangedAction, (state, { payload: progress }) => ({ ...state, progress }));
builder.addCase(fallbackToIntervalAction, (state, { payload: fallbackInterval }) => (
{ ...state, fallbackInterval }
));
builder.addCase(createNewVisits, (state, { payload }) => {
const { tag, visits, query = {} } = state;
const { startDate, endDate } = query;
const newVisits = payload.createdVisits
.filter(({ shortUrl, visit }) => shortUrl?.tags.includes(tag) && isBetween(visit.date, startDate, endDate))
.map(({ visit }) => visit);
return { ...state, visits: [...newVisits, ...visits] };
});
},
});
const { cancelGetTagVisits } = actions;
return { reducer, cancelGetTagVisits };
};

View file

@ -56,23 +56,23 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
// Actions // Actions
bottle.serviceFactory('getShortUrlVisitsCreator', getShortUrlVisits, 'buildShlinkApiClient'); bottle.serviceFactory('getShortUrlVisitsCreator', getShortUrlVisits, 'buildShlinkApiClient');
bottle.serviceFactory('getShortUrlVisits', prop('asyncThunk'), 'getShortUrlVisitsCreator'); bottle.serviceFactory('getShortUrlVisits', prop('asyncThunk'), 'getShortUrlVisitsCreator');
bottle.serviceFactory('cancelGetShortUrlVisits', prop('cancelGetShortUrlVisits'), 'shortUrlVisitsReducerCreator'); bottle.serviceFactory('cancelGetShortUrlVisits', prop('cancelGetVisits'), 'shortUrlVisitsReducerCreator');
bottle.serviceFactory('getTagVisitsCreator', getTagVisits, 'buildShlinkApiClient'); bottle.serviceFactory('getTagVisitsCreator', getTagVisits, 'buildShlinkApiClient');
bottle.serviceFactory('getTagVisits', prop('asyncThunk'), 'getTagVisitsCreator'); bottle.serviceFactory('getTagVisits', prop('asyncThunk'), 'getTagVisitsCreator');
bottle.serviceFactory('cancelGetTagVisits', prop('cancelGetTagVisits'), 'tagVisitsReducerCreator'); bottle.serviceFactory('cancelGetTagVisits', prop('cancelGetVisits'), 'tagVisitsReducerCreator');
bottle.serviceFactory('getDomainVisitsCreator', getDomainVisits, 'buildShlinkApiClient'); bottle.serviceFactory('getDomainVisitsCreator', getDomainVisits, 'buildShlinkApiClient');
bottle.serviceFactory('getDomainVisits', prop('asyncThunk'), 'getDomainVisitsCreator'); bottle.serviceFactory('getDomainVisits', prop('asyncThunk'), 'getDomainVisitsCreator');
bottle.serviceFactory('cancelGetDomainVisits', prop('cancelGetDomainVisits'), 'domainVisitsReducerCreator'); bottle.serviceFactory('cancelGetDomainVisits', prop('cancelGetVisits'), 'domainVisitsReducerCreator');
bottle.serviceFactory('getOrphanVisitsCreator', getOrphanVisits, 'buildShlinkApiClient'); bottle.serviceFactory('getOrphanVisitsCreator', getOrphanVisits, 'buildShlinkApiClient');
bottle.serviceFactory('getOrphanVisits', prop('asyncThunk'), 'getOrphanVisitsCreator'); bottle.serviceFactory('getOrphanVisits', prop('asyncThunk'), 'getOrphanVisitsCreator');
bottle.serviceFactory('cancelGetOrphanVisits', prop('cancelGetOrphanVisits'), 'orphanVisitsReducerCreator'); bottle.serviceFactory('cancelGetOrphanVisits', prop('cancelGetVisits'), 'orphanVisitsReducerCreator');
bottle.serviceFactory('getNonOrphanVisitsCreator', getNonOrphanVisits, 'buildShlinkApiClient'); bottle.serviceFactory('getNonOrphanVisitsCreator', getNonOrphanVisits, 'buildShlinkApiClient');
bottle.serviceFactory('getNonOrphanVisits', prop('asyncThunk'), 'getNonOrphanVisitsCreator'); bottle.serviceFactory('getNonOrphanVisits', prop('asyncThunk'), 'getNonOrphanVisitsCreator');
bottle.serviceFactory('cancelGetNonOrphanVisits', prop('cancelGetNonOrphanVisits'), 'nonOrphanVisitsReducerCreator'); bottle.serviceFactory('cancelGetNonOrphanVisits', prop('cancelGetVisits'), 'nonOrphanVisitsReducerCreator');
bottle.serviceFactory('createNewVisits', () => createNewVisits); bottle.serviceFactory('createNewVisits', () => createNewVisits);
bottle.serviceFactory('loadVisitsOverview', loadVisitsOverview, 'buildShlinkApiClient'); bottle.serviceFactory('loadVisitsOverview', loadVisitsOverview, 'buildShlinkApiClient');

View file

@ -23,7 +23,7 @@ describe('domainVisitsReducer', () => {
const buildApiClientMock = () => Mock.of<ShlinkApiClient>({ getDomainVisits: getDomainVisitsCall }); const buildApiClientMock = () => Mock.of<ShlinkApiClient>({ getDomainVisits: getDomainVisitsCall });
const creator = getDomainVisitsCreator(buildApiClientMock); const creator = getDomainVisitsCreator(buildApiClientMock);
const { asyncThunk: getDomainVisits, progressChangedAction, largeAction, fallbackToIntervalAction } = creator; const { asyncThunk: getDomainVisits, progressChangedAction, largeAction, fallbackToIntervalAction } = creator;
const { reducer, cancelGetDomainVisits } = domainVisitsReducerCreator(creator); const { reducer, cancelGetVisits: cancelGetDomainVisits } = domainVisitsReducerCreator(creator);
beforeEach(jest.clearAllMocks); beforeEach(jest.clearAllMocks);

View file

@ -21,7 +21,7 @@ describe('nonOrphanVisitsReducer', () => {
const buildShlinkApiClient = () => Mock.of<ShlinkApiClient>({ getNonOrphanVisits: getNonOrphanVisitsCall }); const buildShlinkApiClient = () => Mock.of<ShlinkApiClient>({ getNonOrphanVisits: getNonOrphanVisitsCall });
const creator = getNonOrphanVisitsCreator(buildShlinkApiClient); const creator = getNonOrphanVisitsCreator(buildShlinkApiClient);
const { asyncThunk: getNonOrphanVisits, progressChangedAction, largeAction, fallbackToIntervalAction } = creator; const { asyncThunk: getNonOrphanVisits, progressChangedAction, largeAction, fallbackToIntervalAction } = creator;
const { reducer, cancelGetNonOrphanVisits } = nonOrphanVisitsReducerCreator(creator); const { reducer, cancelGetVisits: cancelGetNonOrphanVisits } = nonOrphanVisitsReducerCreator(creator);
beforeEach(jest.clearAllMocks); beforeEach(jest.clearAllMocks);

View file

@ -21,7 +21,7 @@ describe('orphanVisitsReducer', () => {
const buildShlinkApiClientMock = () => Mock.of<ShlinkApiClient>({ getOrphanVisits: getOrphanVisitsCall }); const buildShlinkApiClientMock = () => Mock.of<ShlinkApiClient>({ getOrphanVisits: getOrphanVisitsCall });
const creator = getOrphanVisitsCreator(buildShlinkApiClientMock); const creator = getOrphanVisitsCreator(buildShlinkApiClientMock);
const { asyncThunk: getOrphanVisits, largeAction, progressChangedAction, fallbackToIntervalAction } = creator; const { asyncThunk: getOrphanVisits, largeAction, progressChangedAction, fallbackToIntervalAction } = creator;
const { reducer, cancelGetOrphanVisits } = orphanVisitsReducerCreator(creator); const { reducer, cancelGetVisits: cancelGetOrphanVisits } = orphanVisitsReducerCreator(creator);
beforeEach(jest.clearAllMocks); beforeEach(jest.clearAllMocks);

View file

@ -21,7 +21,7 @@ describe('shortUrlVisitsReducer', () => {
const buildApiClientMock = () => Mock.of<ShlinkApiClient>({ getShortUrlVisits: getShortUrlVisitsCall }); const buildApiClientMock = () => Mock.of<ShlinkApiClient>({ getShortUrlVisits: getShortUrlVisitsCall });
const creator = getShortUrlVisitsCreator(buildApiClientMock); const creator = getShortUrlVisitsCreator(buildApiClientMock);
const { asyncThunk: getShortUrlVisits, largeAction, progressChangedAction, fallbackToIntervalAction } = creator; const { asyncThunk: getShortUrlVisits, largeAction, progressChangedAction, fallbackToIntervalAction } = creator;
const { reducer, cancelGetShortUrlVisits } = shortUrlVisitsReducerCreator(creator); const { reducer, cancelGetVisits: cancelGetShortUrlVisits } = shortUrlVisitsReducerCreator(creator);
beforeEach(jest.clearAllMocks); beforeEach(jest.clearAllMocks);

View file

@ -21,7 +21,7 @@ describe('tagVisitsReducer', () => {
const buildShlinkApiClientMock = () => Mock.of<ShlinkApiClient>({ getTagVisits: getTagVisitsCall }); const buildShlinkApiClientMock = () => Mock.of<ShlinkApiClient>({ getTagVisits: getTagVisitsCall });
const creator = getTagVisitsCreator(buildShlinkApiClientMock); const creator = getTagVisitsCreator(buildShlinkApiClientMock);
const { asyncThunk: getTagVisits, fallbackToIntervalAction, largeAction, progressChangedAction } = creator; const { asyncThunk: getTagVisits, fallbackToIntervalAction, largeAction, progressChangedAction } = creator;
const { reducer, cancelGetTagVisits } = tagVisitsReducerCreator(creator); const { reducer, cancelGetVisits: cancelGetTagVisits } = tagVisitsReducerCreator(creator);
beforeEach(jest.clearAllMocks); beforeEach(jest.clearAllMocks);