Migrated tagVisits reducer to RTK

This commit is contained in:
Alejandro Celaya 2022-11-12 20:02:58 +01:00
parent 3e474a3f2d
commit dac69daf03
11 changed files with 134 additions and 290 deletions

View file

@ -1,7 +0,0 @@
import { Action } from 'redux';
import { ProblemDetailsError } from './errors';
/** @deprecated */
export interface ApiErrorAction extends Action<string> {
errorData?: ProblemDetailsError;
}

View file

@ -1,7 +1,6 @@
import { IContainer } from 'bottlejs'; import { IContainer } from 'bottlejs';
import { combineReducers } from '@reduxjs/toolkit'; import { combineReducers } from '@reduxjs/toolkit';
import { serversReducer } from '../servers/reducers/servers'; import { serversReducer } from '../servers/reducers/servers';
import tagVisitsReducer from '../visits/reducers/tagVisits';
import { settingsReducer } from '../settings/reducers/settings'; import { settingsReducer } from '../settings/reducers/settings';
import { appUpdatesReducer } from '../app/reducers/appUpdates'; import { appUpdatesReducer } from '../app/reducers/appUpdates';
import { sidebarReducer } from '../common/reducers/sidebar'; import { sidebarReducer } from '../common/reducers/sidebar';
@ -16,7 +15,7 @@ export default (container: IContainer) => combineReducers<ShlinkState>({
shortUrlEdition: container.shortUrlEditionReducer, shortUrlEdition: container.shortUrlEditionReducer,
shortUrlDetail: container.shortUrlDetailReducer, shortUrlDetail: container.shortUrlDetailReducer,
shortUrlVisits: container.shortUrlVisitsReducer, shortUrlVisits: container.shortUrlVisitsReducer,
tagVisits: tagVisitsReducer, tagVisits: container.tagVisitsReducer,
domainVisits: container.domainVisitsReducer, domainVisits: container.domainVisitsReducer,
orphanVisits: container.orphanVisitsReducer, orphanVisits: container.orphanVisitsReducer,
nonOrphanVisits: container.nonOrphanVisitsReducer, nonOrphanVisits: container.nonOrphanVisitsReducer,
@ -29,4 +28,4 @@ export default (container: IContainer) => combineReducers<ShlinkState>({
visitsOverview: container.visitsOverviewReducer, visitsOverview: container.visitsOverviewReducer,
appUpdated: appUpdatesReducer, appUpdated: appUpdatesReducer,
sidebar: sidebarReducer, sidebar: sidebarReducer,
} as any); // TODO Fix this });

View file

@ -1,22 +1,6 @@
import { createAsyncThunk as baseCreateAsyncThunk, AsyncThunkPayloadCreator } from '@reduxjs/toolkit'; import { createAsyncThunk as baseCreateAsyncThunk, AsyncThunkPayloadCreator } from '@reduxjs/toolkit';
import { Action } from 'redux';
import { ShlinkState } from '../../container/types'; import { ShlinkState } from '../../container/types';
type ActionHandler<State, AT> = (currentState: State, action: AT) => State;
type ActionHandlerMap<State, AT> = Record<string, ActionHandler<State, AT>>;
/** @deprecated */
export const buildReducer = <State, AT extends Action>(map: ActionHandlerMap<State, AT>, initialState: State) => (
state: State | undefined,
action: AT,
): State => {
const { type } = action;
const actionHandler = map[type];
const currentState = state ?? initialState;
return actionHandler ? actionHandler(currentState, action) : currentState;
};
export const createAsyncThunk = <Returned, ThunkArg>( export const createAsyncThunk = <Returned, ThunkArg>(
typePrefix: string, typePrefix: string,
payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, { state: ShlinkState }>, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, { state: ShlinkState }>,

View file

@ -21,10 +21,6 @@ type Optional<T> = T | null | undefined;
export type OptionalString = Optional<string>; export type OptionalString = Optional<string>;
export type RecursivePartial<T> = {
[P in keyof T]?: RecursivePartial<T[P]>;
};
export const nonEmptyValueOrNull = <T>(value: T): T | null => (isEmpty(value) ? null : value); export const nonEmptyValueOrNull = <T>(value: T): T | null => (isEmpty(value) ? null : value);
export const capitalize = <T extends string>(value: T): string => `${value.charAt(0).toUpperCase()}${value.slice(1)}`; export const capitalize = <T extends string>(value: T): string => `${value.charAt(0).toUpperCase()}${value.slice(1)}`;

View file

@ -1,11 +1,9 @@
import { flatten, prop, range, splitEvery } from 'ramda'; import { flatten, prop, range, splitEvery } from 'ramda';
import { createAction, Dispatch } from '@reduxjs/toolkit'; import { createAction } from '@reduxjs/toolkit';
import { ShlinkPaginator, ShlinkVisits, ShlinkVisitsParams } from '../../api/types'; import { ShlinkPaginator, ShlinkVisits, ShlinkVisitsParams } from '../../api/types';
import { Visit } from '../types'; import { Visit } from '../types';
import { parseApiError } from '../../api/utils';
import { ApiErrorAction } from '../../api/types/actions';
import { DateInterval, dateToMatchingInterval } from '../../utils/dates/types'; import { DateInterval, dateToMatchingInterval } from '../../utils/dates/types';
import { LoadVisits, VisitsLoaded, VisitsLoadProgressChangedAction } from './types'; import { LoadVisits, 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';
@ -26,70 +24,6 @@ interface VisitsAsyncThunkOptions<T extends LoadVisits = LoadVisits, R extends V
shouldCancel: (getState: () => ShlinkState) => boolean; shouldCancel: (getState: () => ShlinkState) => boolean;
} }
export const getVisitsWithLoader = async <T extends VisitsLoaded>(
visitsLoader: VisitsLoader,
lastVisitLoader: LastVisitLoader,
extraFulfilledPayload: Partial<T>,
actionsPrefix: string,
dispatch: Dispatch,
shouldCancel: () => boolean,
) => {
dispatch({ type: `${actionsPrefix}/pending` });
const loadVisitsInParallel = async (pages: number[]): Promise<Visit[]> =>
Promise.all(pages.map(async (page) => visitsLoader(page, ITEMS_PER_PAGE).then(prop('data')))).then(flatten);
const loadPagesBlocks = async (pagesBlocks: number[][], index = 0): Promise<Visit[]> => {
if (shouldCancel()) {
return [];
}
const data = await loadVisitsInParallel(pagesBlocks[index]);
dispatch<VisitsLoadProgressChangedAction>({
type: `${actionsPrefix}/progressChanged`,
payload: calcProgress(pagesBlocks.length, index + PARALLEL_STARTING_PAGE),
});
if (index < pagesBlocks.length - 1) {
return data.concat(await loadPagesBlocks(pagesBlocks, index + 1));
}
return data;
};
const loadVisits = async (page = 1) => {
const { pagination, data } = await visitsLoader(page, ITEMS_PER_PAGE);
// If pagination was not returned, then this is an old shlink version. Just return data
if (!pagination || isLastPage(pagination)) {
return data;
}
// If there are more pages, make requests in blocks of 4
const pagesRange = range(PARALLEL_STARTING_PAGE, pagination.pagesCount + 1);
const pagesBlocks = splitEvery(PARALLEL_REQUESTS_COUNT, pagesRange);
if (pagination.pagesCount - 1 > PARALLEL_REQUESTS_COUNT) {
dispatch({ type: `${actionsPrefix}/large` });
}
return data.concat(await loadPagesBlocks(pagesBlocks));
};
try {
const [visits, lastVisit] = await Promise.all([loadVisits(), lastVisitLoader()]);
dispatch(
!visits.length && lastVisit
? { type: `${actionsPrefix}/fallbackToInterval`, payload: dateToMatchingInterval(lastVisit.date) }
: { type: `${actionsPrefix}/fulfilled`, payload: { ...extraFulfilledPayload, visits } },
);
} catch (e: any) {
dispatch<ApiErrorAction>({ type: `${actionsPrefix}/rejected`, errorData: parseApiError(e) });
}
};
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>, { actionsPrefix, createLoaders, getExtraFulfilledPayload, shouldCancel }: VisitsAsyncThunkOptions<T, R>,
) => { ) => {

View file

@ -1,45 +1,20 @@
import { createAction } from '@reduxjs/toolkit'; import { createSlice } from '@reduxjs/toolkit';
import { Dispatch } from 'redux';
import { buildReducer } from '../../utils/helpers/redux';
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder'; import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
import { GetState } from '../../container/types';
import { ApiErrorAction } from '../../api/types/actions';
import { isBetween } from '../../utils/helpers/date'; import { isBetween } from '../../utils/helpers/date';
import { getVisitsWithLoader, lastVisitLoaderForLoader } from './common'; import { createVisitsAsyncThunk, lastVisitLoaderForLoader } from './common';
import { createNewVisits, CreateVisitsAction } from './visitCreation'; import { createNewVisits } from './visitCreation';
import { import { LoadVisits, VisitsInfo } from './types';
LoadVisits, import { parseApiError } from '../../api/utils';
VisitsFallbackIntervalAction,
VisitsInfo,
VisitsLoaded,
VisitsLoadedAction,
VisitsLoadProgressChangedAction,
} from './types';
const REDUCER_PREFIX = 'shlink/tagVisits'; const REDUCER_PREFIX = 'shlink/tagVisits';
export const GET_TAG_VISITS_START = `${REDUCER_PREFIX}/getTagVisits/pending`;
export const GET_TAG_VISITS_ERROR = `${REDUCER_PREFIX}/getTagVisits/rejected`;
export const GET_TAG_VISITS = `${REDUCER_PREFIX}/getTagVisits/fulfilled`;
export const GET_TAG_VISITS_LARGE = `${REDUCER_PREFIX}/getTagVisits/large`;
export const GET_TAG_VISITS_CANCEL = `${REDUCER_PREFIX}/getTagVisits/cancel`;
export const GET_TAG_VISITS_PROGRESS_CHANGED = `${REDUCER_PREFIX}/getTagVisits/progressChanged`;
export const GET_TAG_VISITS_FALLBACK_TO_INTERVAL = `${REDUCER_PREFIX}/getTagVisits/fallbackToInterval`;
export interface TagVisits extends VisitsInfo { interface WithTag {
tag: string; tag: string;
} }
export interface LoadTagVisits extends LoadVisits { export interface TagVisits extends VisitsInfo, WithTag {}
tag: string;
}
export type TagVisitsAction = VisitsLoadedAction<{ tag: string }>; export interface LoadTagVisits extends LoadVisits, WithTag {}
type TagsVisitsCombinedAction = TagVisitsAction
& VisitsLoadProgressChangedAction
& VisitsFallbackIntervalAction
& CreateVisitsAction
& ApiErrorAction;
const initialState: TagVisits = { const initialState: TagVisits = {
visits: [], visits: [],
@ -51,43 +26,58 @@ const initialState: TagVisits = {
progress: 0, progress: 0,
}; };
export default buildReducer<TagVisits, TagsVisitsCombinedAction>({ export const getTagVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => createVisitsAsyncThunk({
[`${REDUCER_PREFIX}/getTagVisits/pending`]: () => ({ ...initialState, loading: true }), actionsPrefix: `${REDUCER_PREFIX}/getTagVisits`,
[`${REDUCER_PREFIX}/getTagVisits/rejected`]: (_, { errorData }) => ({ ...initialState, error: true, errorData }), createLoaders: ({ tag, query = {}, doIntervalFallback = false }: LoadTagVisits, getState) => {
[`${REDUCER_PREFIX}/getTagVisits/fulfilled`]: (state, { payload }: TagVisitsAction) => ( const { getTagVisits: getVisits } = buildShlinkApiClient(getState);
{ ...state, ...payload, loading: false, loadingLarge: false, error: false } const visitsLoader = async (page: number, itemsPerPage: number) => getVisits(
), tag,
[`${REDUCER_PREFIX}/getTagVisits/large`]: (state) => ({ ...state, loadingLarge: true }), { ...query, page, itemsPerPage },
[`${REDUCER_PREFIX}/getTagVisits/cancel`]: (state) => ({ ...state, cancelLoad: true }), );
[`${REDUCER_PREFIX}/getTagVisits/progressChanged`]: (state, { payload: progress }) => ({ ...state, progress }), const lastVisitLoader = lastVisitLoaderForLoader(doIntervalFallback, async (params) => getVisits(tag, params));
[`${REDUCER_PREFIX}/getTagVisits/fallbackToInterval`]: (state, { payload: fallbackInterval }) => (
{ ...state, fallbackInterval }
),
[createNewVisits.toString()]: (state, { payload }: CreateVisitsAction) => {
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] }; return [visitsLoader, lastVisitLoader];
}, },
}, initialState); getExtraFulfilledPayload: ({ tag, query = {} }: LoadTagVisits) => ({ tag, query }),
shouldCancel: (getState) => getState().tagVisits.cancelLoad,
});
export const getTagVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => ( export const tagVisitsReducerCreator = (
{ tag, query = {}, doIntervalFallback = false }: LoadTagVisits, { asyncThunk, largeAction, progressChangedAction, fallbackToIntervalAction }: ReturnType<typeof getTagVisits>,
) => async (dispatch: Dispatch, getState: GetState) => { ) => {
const { getTagVisits: getVisits } = buildShlinkApiClient(getState); const { reducer, actions } = createSlice({
const visitsLoader = async (page: number, itemsPerPage: number) => getVisits( name: REDUCER_PREFIX,
tag, initialState,
{ ...query, page, itemsPerPage }, reducers: {
); cancelGetTagVisits: (state) => ({ ...state, cancelLoad: true }),
const lastVisitLoader = lastVisitLoaderForLoader(doIntervalFallback, async (params) => getVisits(tag, params)); },
const shouldCancel = () => getState().tagVisits.cancelLoad; extraReducers: (builder) => {
const extraFinishActionData: Partial<VisitsLoaded<{ tag: string }>> = { tag, query }; builder.addCase(asyncThunk.pending, () => ({ ...initialState, loading: true }));
const prefix = `${REDUCER_PREFIX}/getTagVisits`; 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 }
));
return getVisitsWithLoader(visitsLoader, lastVisitLoader, extraFinishActionData, prefix, dispatch, shouldCancel); 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 };
}; };
export const cancelGetTagVisits = createAction<void>(`${REDUCER_PREFIX}/getTagVisits/cancel`);

View file

@ -1,4 +1,3 @@
import { PayloadAction } from '@reduxjs/toolkit';
import { ShlinkVisitsParams } from '../../../api/types'; import { ShlinkVisitsParams } from '../../../api/types';
import { DateInterval } from '../../../utils/dates/types'; import { DateInterval } from '../../../utils/dates/types';
import { ProblemDetailsError } from '../../../api/types/errors'; import { ProblemDetailsError } from '../../../api/types/errors';
@ -25,9 +24,3 @@ export type VisitsLoaded<T = {}> = T & {
visits: Visit[]; visits: Visit[];
query?: ShlinkVisitsParams; query?: ShlinkVisitsParams;
}; };
export type VisitsLoadedAction<T = {}> = PayloadAction<VisitsLoaded<T>>;
export type VisitsLoadProgressChangedAction = PayloadAction<number>;
export type VisitsFallbackIntervalAction = PayloadAction<DateInterval>;

View file

@ -7,7 +7,7 @@ import { TagVisits } from '../TagVisits';
import { OrphanVisits } from '../OrphanVisits'; import { OrphanVisits } from '../OrphanVisits';
import { NonOrphanVisits } from '../NonOrphanVisits'; import { NonOrphanVisits } from '../NonOrphanVisits';
import { getShortUrlVisits, shortUrlVisitsReducerCreator } from '../reducers/shortUrlVisits'; import { getShortUrlVisits, shortUrlVisitsReducerCreator } from '../reducers/shortUrlVisits';
import { cancelGetTagVisits, getTagVisits } from '../reducers/tagVisits'; import { getTagVisits, tagVisitsReducerCreator } from '../reducers/tagVisits';
import { getDomainVisits, domainVisitsReducerCreator } from '../reducers/domainVisits'; import { getDomainVisits, domainVisitsReducerCreator } from '../reducers/domainVisits';
import { getOrphanVisits, orphanVisitsReducerCreator } from '../reducers/orphanVisits'; import { getOrphanVisits, orphanVisitsReducerCreator } from '../reducers/orphanVisits';
import { getNonOrphanVisits, nonOrphanVisitsReducerCreator } from '../reducers/nonOrphanVisits'; import { getNonOrphanVisits, nonOrphanVisitsReducerCreator } from '../reducers/nonOrphanVisits';
@ -58,8 +58,9 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
bottle.serviceFactory('getShortUrlVisits', prop('asyncThunk'), 'getShortUrlVisitsCreator'); bottle.serviceFactory('getShortUrlVisits', prop('asyncThunk'), 'getShortUrlVisitsCreator');
bottle.serviceFactory('cancelGetShortUrlVisits', prop('cancelGetShortUrlVisits'), 'shortUrlVisitsReducerCreator'); bottle.serviceFactory('cancelGetShortUrlVisits', prop('cancelGetShortUrlVisits'), 'shortUrlVisitsReducerCreator');
bottle.serviceFactory('getTagVisits', getTagVisits, 'buildShlinkApiClient'); bottle.serviceFactory('getTagVisitsCreator', getTagVisits, 'buildShlinkApiClient');
bottle.serviceFactory('cancelGetTagVisits', () => cancelGetTagVisits); bottle.serviceFactory('getTagVisits', prop('asyncThunk'), 'getTagVisitsCreator');
bottle.serviceFactory('cancelGetTagVisits', prop('cancelGetTagVisits'), 'tagVisitsReducerCreator');
bottle.serviceFactory('getDomainVisitsCreator', getDomainVisits, 'buildShlinkApiClient'); bottle.serviceFactory('getDomainVisitsCreator', getDomainVisits, 'buildShlinkApiClient');
bottle.serviceFactory('getDomainVisits', prop('asyncThunk'), 'getDomainVisitsCreator'); bottle.serviceFactory('getDomainVisits', prop('asyncThunk'), 'getDomainVisitsCreator');
@ -91,6 +92,9 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
bottle.serviceFactory('shortUrlVisitsReducerCreator', shortUrlVisitsReducerCreator, 'getShortUrlVisitsCreator'); bottle.serviceFactory('shortUrlVisitsReducerCreator', shortUrlVisitsReducerCreator, 'getShortUrlVisitsCreator');
bottle.serviceFactory('shortUrlVisitsReducer', prop('reducer'), 'shortUrlVisitsReducerCreator'); bottle.serviceFactory('shortUrlVisitsReducer', prop('reducer'), 'shortUrlVisitsReducerCreator');
bottle.serviceFactory('tagVisitsReducerCreator', tagVisitsReducerCreator, 'getTagVisitsCreator');
bottle.serviceFactory('tagVisitsReducer', prop('reducer'), 'tagVisitsReducerCreator');
}; };
export default provideServices; export default provideServices;

View file

@ -1,48 +0,0 @@
import { Action } from 'redux';
import { buildReducer } from '../../../src/utils/helpers/redux';
describe('redux', () => {
beforeEach(jest.clearAllMocks);
describe('buildReducer', () => {
const fooActionHandler = jest.fn(() => 'foo result');
const barActionHandler = jest.fn(() => 'bar result');
const initialState = 'initial state';
let reducer: Function;
beforeEach(() => {
reducer = buildReducer<string, Action>({
foo: fooActionHandler,
bar: barActionHandler,
}, initialState);
});
it('returns a reducer which returns initial state when provided with unknown action', () => {
expect(reducer(undefined, { type: 'unknown action' })).toEqual(initialState);
expect(fooActionHandler).not.toHaveBeenCalled();
expect(barActionHandler).not.toHaveBeenCalled();
});
it.each([
['foo', 'foo result', fooActionHandler, barActionHandler],
['bar', 'bar result', barActionHandler, fooActionHandler],
])(
'returns a reducer which calls corresponding action handler',
(type, expected, invokedActionHandler, notInvokedActionHandler) => {
expect(reducer(undefined, { type })).toEqual(expected);
expect(invokedActionHandler).toHaveBeenCalled();
expect(notInvokedActionHandler).not.toHaveBeenCalled();
},
);
it.each([
[undefined, initialState],
['foo', 'foo'],
['something', 'something'],
])('returns a reducer which calls action handler with provided state or initial', (state, expected) => {
reducer(state, { type: 'foo' });
expect(fooActionHandler).toHaveBeenCalledWith(expected, expect.anything());
});
});
});

View file

@ -55,11 +55,10 @@ describe('nonOrphanVisitsReducer', () => {
it('return visits on GET_NON_ORPHAN_VISITS', () => { it('return visits on GET_NON_ORPHAN_VISITS', () => {
const actionVisits = [{}, {}]; const actionVisits = [{}, {}];
const state = reducer(buildState({ loading: true, error: false }), { const { loading, error, visits } = reducer(buildState({ loading: true, error: false }), {
type: getNonOrphanVisits.fulfilled.toString(), type: getNonOrphanVisits.fulfilled.toString(),
payload: { visits: actionVisits }, payload: { visits: actionVisits },
} as any); });
const { loading, error, visits } = state;
expect(loading).toEqual(false); expect(loading).toEqual(false);
expect(error).toEqual(false); expect(error).toEqual(false);
@ -105,13 +104,13 @@ describe('nonOrphanVisitsReducer', () => {
const { visits } = reducer(prevState, { const { visits } = reducer(prevState, {
type: createNewVisits.toString(), type: createNewVisits.toString(),
payload: { createdVisits: [{ visit }, { visit }] }, payload: { createdVisits: [{ visit }, { visit }] },
} as any); });
expect(visits).toHaveLength(expectedVisits); expect(visits).toHaveLength(expectedVisits);
}); });
it('returns new progress on GET_NON_ORPHAN_VISITS_PROGRESS_CHANGED', () => { it('returns new progress on GET_NON_ORPHAN_VISITS_PROGRESS_CHANGED', () => {
const state = reducer(undefined, { type: progressChangedAction.toString(), payload: 85 } as any); const state = reducer(undefined, { type: progressChangedAction.toString(), payload: 85 });
expect(state).toEqual(expect.objectContaining({ progress: 85 })); expect(state).toEqual(expect.objectContaining({ progress: 85 }));
}); });
@ -119,7 +118,7 @@ describe('nonOrphanVisitsReducer', () => {
const fallbackInterval: DateInterval = 'last30Days'; const fallbackInterval: DateInterval = 'last30Days';
const state = reducer( const state = reducer(
undefined, undefined,
{ type: fallbackToIntervalAction.toString(), payload: fallbackInterval } as any, { type: fallbackToIntervalAction.toString(), payload: fallbackInterval },
); );
expect(state).toEqual(expect.objectContaining({ fallbackInterval })); expect(state).toEqual(expect.objectContaining({ fallbackInterval }));

View file

@ -1,15 +1,8 @@
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { addDays, formatISO, subDays } from 'date-fns'; import { addDays, formatISO, subDays } from 'date-fns';
import reducer, { import {
getTagVisits, getTagVisits as getTagVisitsCreator,
cancelGetTagVisits, tagVisitsReducerCreator,
GET_TAG_VISITS_START,
GET_TAG_VISITS_ERROR,
GET_TAG_VISITS,
GET_TAG_VISITS_LARGE,
GET_TAG_VISITS_CANCEL,
GET_TAG_VISITS_PROGRESS_CHANGED,
GET_TAG_VISITS_FALLBACK_TO_INTERVAL,
TagVisits, TagVisits,
} from '../../../src/visits/reducers/tagVisits'; } from '../../../src/visits/reducers/tagVisits';
import { rangeOf } from '../../../src/utils/utils'; import { rangeOf } from '../../../src/utils/utils';
@ -24,34 +17,37 @@ import { createNewVisits } from '../../../src/visits/reducers/visitCreation';
describe('tagVisitsReducer', () => { describe('tagVisitsReducer', () => {
const now = new Date(); const now = new Date();
const visitsMocks = rangeOf(2, () => Mock.all<Visit>()); const visitsMocks = rangeOf(2, () => Mock.all<Visit>());
const getTagVisitsCall = jest.fn();
const buildShlinkApiClientMock = () => Mock.of<ShlinkApiClient>({ getTagVisits: getTagVisitsCall });
const creator = getTagVisitsCreator(buildShlinkApiClientMock);
const { asyncThunk: getTagVisits, fallbackToIntervalAction, largeAction, progressChangedAction } = creator;
const { reducer, cancelGetTagVisits } = tagVisitsReducerCreator(creator);
beforeEach(jest.clearAllMocks);
describe('reducer', () => { describe('reducer', () => {
const buildState = (data: Partial<TagVisits>) => Mock.of<TagVisits>(data); const buildState = (data: Partial<TagVisits>) => Mock.of<TagVisits>(data);
it('returns loading on GET_TAG_VISITS_START', () => { it('returns loading on GET_TAG_VISITS_START', () => {
const state = reducer(buildState({ loading: false }), { type: GET_TAG_VISITS_START } as any); const { loading } = reducer(buildState({ loading: false }), { type: getTagVisits.pending.toString() });
const { loading } = state;
expect(loading).toEqual(true); expect(loading).toEqual(true);
}); });
it('returns loadingLarge on GET_TAG_VISITS_LARGE', () => { it('returns loadingLarge on GET_TAG_VISITS_LARGE', () => {
const state = reducer(buildState({ loadingLarge: false }), { type: GET_TAG_VISITS_LARGE } as any); const { loadingLarge } = reducer(buildState({ loadingLarge: false }), { type: largeAction.toString() });
const { loadingLarge } = state;
expect(loadingLarge).toEqual(true); expect(loadingLarge).toEqual(true);
}); });
it('returns cancelLoad on GET_TAG_VISITS_CANCEL', () => { it('returns cancelLoad on GET_TAG_VISITS_CANCEL', () => {
const state = reducer(buildState({ cancelLoad: false }), { type: GET_TAG_VISITS_CANCEL } as any); const { cancelLoad } = reducer(buildState({ cancelLoad: false }), { type: cancelGetTagVisits.toString() });
const { cancelLoad } = state;
expect(cancelLoad).toEqual(true); expect(cancelLoad).toEqual(true);
}); });
it('stops loading and returns error on GET_TAG_VISITS_ERROR', () => { it('stops loading and returns error on GET_TAG_VISITS_ERROR', () => {
const state = reducer(buildState({ loading: true, error: false }), { type: GET_TAG_VISITS_ERROR } as any); const { loading, error } = reducer(
const { loading, error } = state; buildState({ loading: true, error: false }),
{ type: getTagVisits.rejected.toString() },
);
expect(loading).toEqual(false); expect(loading).toEqual(false);
expect(error).toEqual(true); expect(error).toEqual(true);
@ -59,11 +55,10 @@ describe('tagVisitsReducer', () => {
it('return visits on GET_TAG_VISITS', () => { it('return visits on GET_TAG_VISITS', () => {
const actionVisits = [{}, {}]; const actionVisits = [{}, {}];
const state = reducer(buildState({ loading: true, error: false }), { const { loading, error, visits } = reducer(buildState({ loading: true, error: false }), {
type: GET_TAG_VISITS, type: getTagVisits.fulfilled.toString(),
payload: { visits: actionVisits }, payload: { visits: actionVisits },
} as any); });
const { loading, error, visits } = state;
expect(loading).toEqual(false); expect(loading).toEqual(false);
expect(error).toEqual(false); expect(error).toEqual(false);
@ -129,48 +124,44 @@ describe('tagVisitsReducer', () => {
const { visits } = reducer(prevState, { const { visits } = reducer(prevState, {
type: createNewVisits.toString(), type: createNewVisits.toString(),
payload: { createdVisits: [{ shortUrl, visit: { date: formatIsoDate(now) ?? undefined } }] }, payload: { createdVisits: [{ shortUrl, visit: { date: formatIsoDate(now) ?? undefined } }] },
} as any); });
expect(visits).toHaveLength(expectedVisits); expect(visits).toHaveLength(expectedVisits);
}); });
it('returns new progress on GET_TAG_VISITS_PROGRESS_CHANGED', () => { it('returns new progress on GET_TAG_VISITS_PROGRESS_CHANGED', () => {
const state = reducer(undefined, { type: GET_TAG_VISITS_PROGRESS_CHANGED, payload: 85 } as any); const state = reducer(undefined, { type: progressChangedAction.toString(), payload: 85 });
expect(state).toEqual(expect.objectContaining({ progress: 85 })); expect(state).toEqual(expect.objectContaining({ progress: 85 }));
}); });
it('returns fallbackInterval on GET_TAG_VISITS_FALLBACK_TO_INTERVAL', () => { it('returns fallbackInterval on GET_TAG_VISITS_FALLBACK_TO_INTERVAL', () => {
const fallbackInterval: DateInterval = 'last30Days'; const fallbackInterval: DateInterval = 'last30Days';
const state = reducer(undefined, { type: GET_TAG_VISITS_FALLBACK_TO_INTERVAL, payload: fallbackInterval } as any); const state = reducer(undefined, { type: fallbackToIntervalAction.toString(), payload: fallbackInterval });
expect(state).toEqual(expect.objectContaining({ fallbackInterval })); expect(state).toEqual(expect.objectContaining({ fallbackInterval }));
}); });
}); });
describe('getTagVisits', () => { describe('getTagVisits', () => {
type GetVisitsReturn = Promise<ShlinkVisits> | ((shortCode: string, query: any) => Promise<ShlinkVisits>);
const buildApiClientMock = (returned: GetVisitsReturn) => Mock.of<ShlinkApiClient>({
getTagVisits: jest.fn(typeof returned === 'function' ? returned : async () => returned),
});
const dispatchMock = jest.fn(); const dispatchMock = jest.fn();
const getState = () => Mock.of<ShlinkState>({ const getState = () => Mock.of<ShlinkState>({
tagVisits: { cancelLoad: false }, tagVisits: { cancelLoad: false },
}); });
const tag = 'foo'; const tag = 'foo';
beforeEach(jest.clearAllMocks);
it('dispatches start and error when promise is rejected', async () => { it('dispatches start and error when promise is rejected', async () => {
const shlinkApiClient = buildApiClientMock(Promise.reject(new Error())); getTagVisitsCall.mockRejectedValue(new Error());
await getTagVisits(() => shlinkApiClient)({ tag })(dispatchMock, getState); await getTagVisits({ tag })(dispatchMock, getState, {});
expect(dispatchMock).toHaveBeenCalledTimes(2); expect(dispatchMock).toHaveBeenCalledTimes(2);
expect(dispatchMock).toHaveBeenNthCalledWith(1, { type: GET_TAG_VISITS_START }); expect(dispatchMock).toHaveBeenNthCalledWith(1, expect.objectContaining({
expect(dispatchMock).toHaveBeenNthCalledWith(2, { type: GET_TAG_VISITS_ERROR }); type: getTagVisits.pending.toString(),
expect(shlinkApiClient.getTagVisits).toHaveBeenCalledTimes(1); }));
expect(dispatchMock).toHaveBeenNthCalledWith(2, expect.objectContaining({
type: getTagVisits.rejected.toString(),
}));
expect(getTagVisitsCall).toHaveBeenCalledTimes(1);
}); });
it.each([ it.each([
@ -178,37 +169,45 @@ describe('tagVisitsReducer', () => {
[{}], [{}],
])('dispatches start and success when promise is resolved', async (query) => { ])('dispatches start and success when promise is resolved', async (query) => {
const visits = visitsMocks; const visits = visitsMocks;
const shlinkApiClient = buildApiClientMock(Promise.resolve({ getTagVisitsCall.mockResolvedValue({
data: visitsMocks, data: visitsMocks,
pagination: { pagination: {
currentPage: 1, currentPage: 1,
pagesCount: 1, pagesCount: 1,
totalItems: 1, totalItems: 1,
}, },
})); });
await getTagVisits(() => shlinkApiClient)({ tag, query })(dispatchMock, getState); await getTagVisits({ tag, query })(dispatchMock, getState, {});
expect(dispatchMock).toHaveBeenCalledTimes(2); expect(dispatchMock).toHaveBeenCalledTimes(2);
expect(dispatchMock).toHaveBeenNthCalledWith(1, { type: GET_TAG_VISITS_START }); expect(dispatchMock).toHaveBeenNthCalledWith(1, expect.objectContaining({
expect(dispatchMock).toHaveBeenNthCalledWith(2, { type: getTagVisits.pending.toString(),
type: GET_TAG_VISITS, }));
expect(dispatchMock).toHaveBeenNthCalledWith(2, expect.objectContaining({
type: getTagVisits.fulfilled.toString(),
payload: { visits, tag, query: query ?? {} }, payload: { visits, tag, query: query ?? {} },
}); }));
expect(shlinkApiClient.getTagVisits).toHaveBeenCalledTimes(1); expect(getTagVisitsCall).toHaveBeenCalledTimes(1);
}); });
it.each([ it.each([
[ [
[Mock.of<Visit>({ date: formatISO(subDays(new Date(), 20)) })], [Mock.of<Visit>({ date: formatISO(subDays(new Date(), 20)) })],
{ type: GET_TAG_VISITS_FALLBACK_TO_INTERVAL, payload: 'last30Days' }, { type: fallbackToIntervalAction.toString(), payload: 'last30Days' },
3,
], ],
[ [
[Mock.of<Visit>({ date: formatISO(subDays(new Date(), 100)) })], [Mock.of<Visit>({ date: formatISO(subDays(new Date(), 100)) })],
{ type: GET_TAG_VISITS_FALLBACK_TO_INTERVAL, payload: 'last180Days' }, { type: fallbackToIntervalAction.toString(), payload: 'last180Days' },
3,
], ],
[[], expect.objectContaining({ type: GET_TAG_VISITS })], [[], expect.objectContaining({ type: getTagVisits.fulfilled.toString() }), 2],
])('dispatches fallback interval when the list of visits is empty', async (lastVisits, expectedSecondDispatch) => { ])('dispatches fallback interval when the list of visits is empty', async (
lastVisits,
expectedSecondDispatch,
expectedDispatchCalls,
) => {
const buildVisitsResult = (data: Visit[] = []): ShlinkVisits => ({ const buildVisitsResult = (data: Visit[] = []): ShlinkVisits => ({
data, data,
pagination: { pagination: {
@ -217,22 +216,23 @@ describe('tagVisitsReducer', () => {
totalItems: 1, totalItems: 1,
}, },
}); });
const getShlinkTagVisits = jest.fn() getTagVisitsCall
.mockResolvedValueOnce(buildVisitsResult()) .mockResolvedValueOnce(buildVisitsResult())
.mockResolvedValueOnce(buildVisitsResult(lastVisits)); .mockResolvedValueOnce(buildVisitsResult(lastVisits));
const ShlinkApiClient = Mock.of<ShlinkApiClient>({ getTagVisits: getShlinkTagVisits });
await getTagVisits(() => ShlinkApiClient)({ tag, doIntervalFallback: true })(dispatchMock, getState); await getTagVisits({ tag, doIntervalFallback: true })(dispatchMock, getState, {});
expect(dispatchMock).toHaveBeenCalledTimes(2); expect(dispatchMock).toHaveBeenCalledTimes(expectedDispatchCalls);
expect(dispatchMock).toHaveBeenNthCalledWith(1, { type: GET_TAG_VISITS_START }); expect(dispatchMock).toHaveBeenNthCalledWith(1, expect.objectContaining({
type: getTagVisits.pending.toString(),
}));
expect(dispatchMock).toHaveBeenNthCalledWith(2, expectedSecondDispatch); expect(dispatchMock).toHaveBeenNthCalledWith(2, expectedSecondDispatch);
expect(getShlinkTagVisits).toHaveBeenCalledTimes(2); expect(getTagVisitsCall).toHaveBeenCalledTimes(2);
}); });
}); });
describe('cancelGetTagVisits', () => { describe('cancelGetTagVisits', () => {
it('just returns the action with proper type', () => it('just returns the action with proper type', () =>
expect(cancelGetTagVisits()).toEqual({ type: GET_TAG_VISITS_CANCEL })); expect(cancelGetTagVisits()).toEqual({ type: cancelGetTagVisits.toString() }));
}); });
}); });