mirror of
https://github.com/shlinkio/shlink-web-client.git
synced 2026-04-19 13:06:22 +00:00
Migrated tagVisits reducer to RTK
This commit is contained in:
@@ -1,7 +0,0 @@
|
||||
import { Action } from 'redux';
|
||||
import { ProblemDetailsError } from './errors';
|
||||
|
||||
/** @deprecated */
|
||||
export interface ApiErrorAction extends Action<string> {
|
||||
errorData?: ProblemDetailsError;
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { IContainer } from 'bottlejs';
|
||||
import { combineReducers } from '@reduxjs/toolkit';
|
||||
import { serversReducer } from '../servers/reducers/servers';
|
||||
import tagVisitsReducer from '../visits/reducers/tagVisits';
|
||||
import { settingsReducer } from '../settings/reducers/settings';
|
||||
import { appUpdatesReducer } from '../app/reducers/appUpdates';
|
||||
import { sidebarReducer } from '../common/reducers/sidebar';
|
||||
@@ -16,7 +15,7 @@ export default (container: IContainer) => combineReducers<ShlinkState>({
|
||||
shortUrlEdition: container.shortUrlEditionReducer,
|
||||
shortUrlDetail: container.shortUrlDetailReducer,
|
||||
shortUrlVisits: container.shortUrlVisitsReducer,
|
||||
tagVisits: tagVisitsReducer,
|
||||
tagVisits: container.tagVisitsReducer,
|
||||
domainVisits: container.domainVisitsReducer,
|
||||
orphanVisits: container.orphanVisitsReducer,
|
||||
nonOrphanVisits: container.nonOrphanVisitsReducer,
|
||||
@@ -29,4 +28,4 @@ export default (container: IContainer) => combineReducers<ShlinkState>({
|
||||
visitsOverview: container.visitsOverviewReducer,
|
||||
appUpdated: appUpdatesReducer,
|
||||
sidebar: sidebarReducer,
|
||||
} as any); // TODO Fix this
|
||||
});
|
||||
|
||||
@@ -1,22 +1,6 @@
|
||||
import { createAsyncThunk as baseCreateAsyncThunk, AsyncThunkPayloadCreator } from '@reduxjs/toolkit';
|
||||
import { Action } from 'redux';
|
||||
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>(
|
||||
typePrefix: string,
|
||||
payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, { state: ShlinkState }>,
|
||||
|
||||
@@ -21,10 +21,6 @@ type Optional<T> = T | null | undefined;
|
||||
|
||||
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 capitalize = <T extends string>(value: T): string => `${value.charAt(0).toUpperCase()}${value.slice(1)}`;
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
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 { Visit } from '../types';
|
||||
import { parseApiError } from '../../api/utils';
|
||||
import { ApiErrorAction } from '../../api/types/actions';
|
||||
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 { ShlinkState } from '../../container/types';
|
||||
|
||||
@@ -26,70 +24,6 @@ interface VisitsAsyncThunkOptions<T extends LoadVisits = LoadVisits, R extends V
|
||||
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>(
|
||||
{ actionsPrefix, createLoaders, getExtraFulfilledPayload, shouldCancel }: VisitsAsyncThunkOptions<T, R>,
|
||||
) => {
|
||||
|
||||
@@ -1,45 +1,20 @@
|
||||
import { createAction } from '@reduxjs/toolkit';
|
||||
import { Dispatch } from 'redux';
|
||||
import { buildReducer } from '../../utils/helpers/redux';
|
||||
import { createSlice } from '@reduxjs/toolkit';
|
||||
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
|
||||
import { GetState } from '../../container/types';
|
||||
import { ApiErrorAction } from '../../api/types/actions';
|
||||
import { isBetween } from '../../utils/helpers/date';
|
||||
import { getVisitsWithLoader, lastVisitLoaderForLoader } from './common';
|
||||
import { createNewVisits, CreateVisitsAction } from './visitCreation';
|
||||
import {
|
||||
LoadVisits,
|
||||
VisitsFallbackIntervalAction,
|
||||
VisitsInfo,
|
||||
VisitsLoaded,
|
||||
VisitsLoadedAction,
|
||||
VisitsLoadProgressChangedAction,
|
||||
} from './types';
|
||||
import { createVisitsAsyncThunk, lastVisitLoaderForLoader } from './common';
|
||||
import { createNewVisits } from './visitCreation';
|
||||
import { LoadVisits, VisitsInfo } from './types';
|
||||
import { parseApiError } from '../../api/utils';
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
export interface LoadTagVisits extends LoadVisits {
|
||||
tag: string;
|
||||
}
|
||||
export interface TagVisits extends VisitsInfo, WithTag {}
|
||||
|
||||
export type TagVisitsAction = VisitsLoadedAction<{ tag: string }>;
|
||||
|
||||
type TagsVisitsCombinedAction = TagVisitsAction
|
||||
& VisitsLoadProgressChangedAction
|
||||
& VisitsFallbackIntervalAction
|
||||
& CreateVisitsAction
|
||||
& ApiErrorAction;
|
||||
export interface LoadTagVisits extends LoadVisits, WithTag {}
|
||||
|
||||
const initialState: TagVisits = {
|
||||
visits: [],
|
||||
@@ -51,43 +26,58 @@ const initialState: TagVisits = {
|
||||
progress: 0,
|
||||
};
|
||||
|
||||
export default buildReducer<TagVisits, TagsVisitsCombinedAction>({
|
||||
[`${REDUCER_PREFIX}/getTagVisits/pending`]: () => ({ ...initialState, loading: true }),
|
||||
[`${REDUCER_PREFIX}/getTagVisits/rejected`]: (_, { errorData }) => ({ ...initialState, error: true, errorData }),
|
||||
[`${REDUCER_PREFIX}/getTagVisits/fulfilled`]: (state, { payload }: TagVisitsAction) => (
|
||||
{ ...state, ...payload, loading: false, loadingLarge: false, error: false }
|
||||
),
|
||||
[`${REDUCER_PREFIX}/getTagVisits/large`]: (state) => ({ ...state, loadingLarge: true }),
|
||||
[`${REDUCER_PREFIX}/getTagVisits/cancel`]: (state) => ({ ...state, cancelLoad: true }),
|
||||
[`${REDUCER_PREFIX}/getTagVisits/progressChanged`]: (state, { payload: progress }) => ({ ...state, progress }),
|
||||
[`${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);
|
||||
export const getTagVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => createVisitsAsyncThunk({
|
||||
actionsPrefix: `${REDUCER_PREFIX}/getTagVisits`,
|
||||
createLoaders: ({ tag, query = {}, doIntervalFallback = false }: LoadTagVisits, getState) => {
|
||||
const { getTagVisits: getVisits } = buildShlinkApiClient(getState);
|
||||
const visitsLoader = async (page: number, itemsPerPage: number) => getVisits(
|
||||
tag,
|
||||
{ ...query, page, itemsPerPage },
|
||||
);
|
||||
const lastVisitLoader = lastVisitLoaderForLoader(doIntervalFallback, async (params) => getVisits(tag, params));
|
||||
|
||||
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) => (
|
||||
{ tag, query = {}, doIntervalFallback = false }: LoadTagVisits,
|
||||
) => async (dispatch: Dispatch, getState: GetState) => {
|
||||
const { getTagVisits: getVisits } = buildShlinkApiClient(getState);
|
||||
const visitsLoader = async (page: number, itemsPerPage: number) => getVisits(
|
||||
tag,
|
||||
{ ...query, page, itemsPerPage },
|
||||
);
|
||||
const lastVisitLoader = lastVisitLoaderForLoader(doIntervalFallback, async (params) => getVisits(tag, params));
|
||||
const shouldCancel = () => getState().tagVisits.cancelLoad;
|
||||
const extraFinishActionData: Partial<VisitsLoaded<{ tag: string }>> = { tag, query };
|
||||
const prefix = `${REDUCER_PREFIX}/getTagVisits`;
|
||||
export const tagVisitsReducerCreator = (
|
||||
{ asyncThunk, largeAction, progressChangedAction, fallbackToIntervalAction }: ReturnType<typeof getTagVisits>,
|
||||
) => {
|
||||
const { reducer, actions } = createSlice({
|
||||
name: REDUCER_PREFIX,
|
||||
initialState,
|
||||
reducers: {
|
||||
cancelGetTagVisits: (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 }
|
||||
));
|
||||
|
||||
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`);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { PayloadAction } from '@reduxjs/toolkit';
|
||||
import { ShlinkVisitsParams } from '../../../api/types';
|
||||
import { DateInterval } from '../../../utils/dates/types';
|
||||
import { ProblemDetailsError } from '../../../api/types/errors';
|
||||
@@ -25,9 +24,3 @@ export type VisitsLoaded<T = {}> = T & {
|
||||
visits: Visit[];
|
||||
query?: ShlinkVisitsParams;
|
||||
};
|
||||
|
||||
export type VisitsLoadedAction<T = {}> = PayloadAction<VisitsLoaded<T>>;
|
||||
|
||||
export type VisitsLoadProgressChangedAction = PayloadAction<number>;
|
||||
|
||||
export type VisitsFallbackIntervalAction = PayloadAction<DateInterval>;
|
||||
|
||||
@@ -7,7 +7,7 @@ import { TagVisits } from '../TagVisits';
|
||||
import { OrphanVisits } from '../OrphanVisits';
|
||||
import { NonOrphanVisits } from '../NonOrphanVisits';
|
||||
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 { getOrphanVisits, orphanVisitsReducerCreator } from '../reducers/orphanVisits';
|
||||
import { getNonOrphanVisits, nonOrphanVisitsReducerCreator } from '../reducers/nonOrphanVisits';
|
||||
@@ -58,8 +58,9 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
|
||||
bottle.serviceFactory('getShortUrlVisits', prop('asyncThunk'), 'getShortUrlVisitsCreator');
|
||||
bottle.serviceFactory('cancelGetShortUrlVisits', prop('cancelGetShortUrlVisits'), 'shortUrlVisitsReducerCreator');
|
||||
|
||||
bottle.serviceFactory('getTagVisits', getTagVisits, 'buildShlinkApiClient');
|
||||
bottle.serviceFactory('cancelGetTagVisits', () => cancelGetTagVisits);
|
||||
bottle.serviceFactory('getTagVisitsCreator', getTagVisits, 'buildShlinkApiClient');
|
||||
bottle.serviceFactory('getTagVisits', prop('asyncThunk'), 'getTagVisitsCreator');
|
||||
bottle.serviceFactory('cancelGetTagVisits', prop('cancelGetTagVisits'), 'tagVisitsReducerCreator');
|
||||
|
||||
bottle.serviceFactory('getDomainVisitsCreator', getDomainVisits, 'buildShlinkApiClient');
|
||||
bottle.serviceFactory('getDomainVisits', prop('asyncThunk'), 'getDomainVisitsCreator');
|
||||
@@ -91,6 +92,9 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
|
||||
|
||||
bottle.serviceFactory('shortUrlVisitsReducerCreator', shortUrlVisitsReducerCreator, 'getShortUrlVisitsCreator');
|
||||
bottle.serviceFactory('shortUrlVisitsReducer', prop('reducer'), 'shortUrlVisitsReducerCreator');
|
||||
|
||||
bottle.serviceFactory('tagVisitsReducerCreator', tagVisitsReducerCreator, 'getTagVisitsCreator');
|
||||
bottle.serviceFactory('tagVisitsReducer', prop('reducer'), 'tagVisitsReducerCreator');
|
||||
};
|
||||
|
||||
export default provideServices;
|
||||
|
||||
Reference in New Issue
Block a user