2022-11-12 22:37:04 +03:00
|
|
|
import { createAction, createSlice } from '@reduxjs/toolkit';
|
2023-02-18 13:11:01 +03:00
|
|
|
import { flatten, prop, range, splitEvery } from 'ramda';
|
2023-07-24 21:14:59 +03:00
|
|
|
import type { ShlinkState } from '../../../src/container/types';
|
|
|
|
import type { DateInterval } from '../../../src/utils/helpers/dateIntervals';
|
|
|
|
import { dateToMatchingInterval } from '../../../src/utils/helpers/dateIntervals';
|
|
|
|
import { createAsyncThunk } from '../../../src/utils/helpers/redux';
|
2023-07-24 18:30:58 +03:00
|
|
|
import type { ShlinkPaginator, ShlinkVisits, ShlinkVisitsParams } from '../../api-contract';
|
|
|
|
import { parseApiError } from '../../api-contract/utils';
|
2023-02-18 13:11:01 +03:00
|
|
|
import type { CreateVisit, Visit } from '../types';
|
|
|
|
import type { LoadVisits, VisitsInfo, VisitsLoaded } from './types';
|
2022-11-12 22:37:04 +03:00
|
|
|
import { createNewVisits } from './visitCreation';
|
2020-05-10 20:02:58 +03:00
|
|
|
|
|
|
|
const ITEMS_PER_PAGE = 5000;
|
2020-05-11 20:32:42 +03:00
|
|
|
const PARALLEL_REQUESTS_COUNT = 4;
|
|
|
|
const PARALLEL_STARTING_PAGE = 2;
|
|
|
|
|
2020-08-28 19:33:37 +03:00
|
|
|
const isLastPage = ({ currentPage, pagesCount }: ShlinkPaginator): boolean => currentPage >= pagesCount;
|
2022-03-26 14:17:42 +03:00
|
|
|
const calcProgress = (total: number, current: number): number => (current * 100) / total;
|
2020-08-28 19:33:37 +03:00
|
|
|
|
|
|
|
type VisitsLoader = (page: number, itemsPerPage: number) => Promise<ShlinkVisits>;
|
2023-03-10 10:53:05 +03:00
|
|
|
type LastVisitLoader = (excludeBots?: boolean) => Promise<Visit | undefined>;
|
2020-08-28 19:33:37 +03:00
|
|
|
|
2022-11-12 19:51:37 +03:00
|
|
|
interface VisitsAsyncThunkOptions<T extends LoadVisits = LoadVisits, R extends VisitsLoaded = VisitsLoaded> {
|
2022-11-13 11:59:49 +03:00
|
|
|
typePrefix: string;
|
2023-07-24 10:48:41 +03:00
|
|
|
createLoaders: (params: T) => [VisitsLoader, LastVisitLoader];
|
2022-11-12 19:51:37 +03:00
|
|
|
getExtraFulfilledPayload: (params: T) => Partial<R>;
|
|
|
|
shouldCancel: (getState: () => ShlinkState) => boolean;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const createVisitsAsyncThunk = <T extends LoadVisits = LoadVisits, R extends VisitsLoaded = VisitsLoaded>(
|
2022-11-13 11:59:49 +03:00
|
|
|
{ typePrefix, createLoaders, getExtraFulfilledPayload, shouldCancel }: VisitsAsyncThunkOptions<T, R>,
|
2022-11-12 19:51:37 +03:00
|
|
|
) => {
|
2022-12-31 12:34:29 +03:00
|
|
|
const progressChanged = createAction<number>(`${typePrefix}/progressChanged`);
|
|
|
|
const large = createAction<void>(`${typePrefix}/large`);
|
|
|
|
const fallbackToInterval = createAction<DateInterval>(`${typePrefix}/fallbackToInterval`);
|
2022-11-12 19:51:37 +03:00
|
|
|
|
2022-12-31 12:34:29 +03:00
|
|
|
const asyncThunk = createAsyncThunk(typePrefix, async (params: T, { getState, dispatch }): Promise<Partial<R>> => {
|
2023-07-24 10:48:41 +03:00
|
|
|
const [visitsLoader, lastVisitLoader] = createLoaders(params);
|
2022-11-12 19:51:37 +03:00
|
|
|
|
|
|
|
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(getState)) {
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
|
|
|
const data = await loadVisitsInParallel(pagesBlocks[index]);
|
|
|
|
|
2022-12-31 12:34:29 +03:00
|
|
|
dispatch(progressChanged(calcProgress(pagesBlocks.length, index + PARALLEL_STARTING_PAGE)));
|
2022-11-12 19:51:37 +03:00
|
|
|
|
|
|
|
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) {
|
2022-12-31 12:34:29 +03:00
|
|
|
dispatch(large());
|
2022-11-12 19:51:37 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return data.concat(await loadPagesBlocks(pagesBlocks));
|
|
|
|
};
|
|
|
|
|
2023-03-10 10:53:05 +03:00
|
|
|
const [visits, lastVisit] = await Promise.all([loadVisits(), lastVisitLoader(params.query?.excludeBots)]);
|
2022-11-12 19:51:37 +03:00
|
|
|
|
|
|
|
if (!visits.length && lastVisit) {
|
2022-12-31 12:34:29 +03:00
|
|
|
dispatch(fallbackToInterval(dateToMatchingInterval(lastVisit.date)));
|
2022-11-12 19:51:37 +03:00
|
|
|
}
|
|
|
|
|
2022-12-31 12:34:29 +03:00
|
|
|
return { ...getExtraFulfilledPayload(params), visits };
|
2022-11-12 19:51:37 +03:00
|
|
|
});
|
|
|
|
|
2022-12-31 12:34:29 +03:00
|
|
|
// Enhance the async thunk with extra actions
|
|
|
|
return Object.assign(asyncThunk, { progressChanged, large, fallbackToInterval });
|
2022-11-12 19:51:37 +03:00
|
|
|
};
|
|
|
|
|
2021-12-23 12:38:02 +03:00
|
|
|
export const lastVisitLoaderForLoader = (
|
2021-12-23 12:51:13 +03:00
|
|
|
doIntervalFallback: boolean,
|
2021-12-23 12:38:02 +03:00
|
|
|
loader: (params: ShlinkVisitsParams) => Promise<ShlinkVisits>,
|
2023-03-10 10:53:05 +03:00
|
|
|
): LastVisitLoader => async (excludeBots?: boolean) => (
|
|
|
|
!doIntervalFallback
|
|
|
|
? Promise.resolve(undefined)
|
|
|
|
: loader({ page: 1, itemsPerPage: 1, excludeBots }).then(({ data }) => data[0])
|
|
|
|
);
|
2022-11-12 22:37:04 +03:00
|
|
|
|
2022-11-13 11:59:49 +03:00
|
|
|
interface VisitsReducerOptions<State extends VisitsInfo, AT extends ReturnType<typeof createVisitsAsyncThunk>> {
|
|
|
|
name: string;
|
|
|
|
asyncThunkCreator: AT;
|
|
|
|
initialState: State;
|
|
|
|
filterCreatedVisits: (state: State, createdVisits: CreateVisit[]) => CreateVisit[];
|
|
|
|
}
|
|
|
|
|
2022-11-12 22:37:04 +03:00
|
|
|
export const createVisitsReducer = <State extends VisitsInfo, AT extends ReturnType<typeof createVisitsAsyncThunk>>(
|
2022-11-13 11:59:49 +03:00
|
|
|
{ name, asyncThunkCreator, initialState, filterCreatedVisits }: VisitsReducerOptions<State, AT>,
|
2022-11-12 22:37:04 +03:00
|
|
|
) => {
|
2022-12-31 12:34:29 +03:00
|
|
|
const { pending, rejected, fulfilled, large, progressChanged, fallbackToInterval } = asyncThunkCreator;
|
2022-11-12 22:37:04 +03:00
|
|
|
const { reducer, actions } = createSlice({
|
|
|
|
name,
|
|
|
|
initialState,
|
|
|
|
reducers: {
|
|
|
|
cancelGetVisits: (state) => ({ ...state, cancelLoad: true }),
|
|
|
|
},
|
|
|
|
extraReducers: (builder) => {
|
2022-12-31 12:34:29 +03:00
|
|
|
builder.addCase(pending, () => ({ ...initialState, loading: true }));
|
|
|
|
builder.addCase(rejected, (_, { error }) => (
|
2022-11-12 22:37:04 +03:00
|
|
|
{ ...initialState, error: true, errorData: parseApiError(error) }
|
|
|
|
));
|
2022-12-31 12:34:29 +03:00
|
|
|
builder.addCase(fulfilled, (state, { payload }) => (
|
2022-11-12 22:37:04 +03:00
|
|
|
{ ...state, ...payload, loading: false, loadingLarge: false, error: false }
|
|
|
|
));
|
|
|
|
|
2022-12-31 12:34:29 +03:00
|
|
|
builder.addCase(large, (state) => ({ ...state, loadingLarge: true }));
|
|
|
|
builder.addCase(progressChanged, (state, { payload: progress }) => ({ ...state, progress }));
|
|
|
|
builder.addCase(fallbackToInterval, (state, { payload: fallbackInterval }) => (
|
2022-11-12 22:37:04 +03:00
|
|
|
{ ...state, fallbackInterval }
|
|
|
|
));
|
|
|
|
|
|
|
|
builder.addCase(createNewVisits, (state, { payload }) => {
|
|
|
|
const { visits } = state;
|
2022-11-13 11:59:49 +03:00
|
|
|
// @ts-expect-error TODO Fix type inference
|
2022-11-12 22:37:04 +03:00
|
|
|
const newVisits = filterCreatedVisits(state, payload.createdVisits).map(({ visit }) => visit);
|
|
|
|
|
2022-11-13 11:59:49 +03:00
|
|
|
return !newVisits.length ? state : { ...state, visits: [...newVisits, ...visits] };
|
2022-11-12 22:37:04 +03:00
|
|
|
});
|
|
|
|
},
|
|
|
|
});
|
|
|
|
const { cancelGetVisits } = actions;
|
|
|
|
|
|
|
|
return { reducer, cancelGetVisits };
|
|
|
|
};
|