shlink-web-client/src/visits/reducers/orphanVisits.ts

55 lines
2.1 KiB
TypeScript
Raw Normal View History

import { OrphanVisit, OrphanVisitType } from '../types';
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
import { isOrphanVisit } from '../types/helpers';
import { isBetween } from '../../utils/helpers/date';
import { createVisitsAsyncThunk, createVisitsReducer, lastVisitLoaderForLoader } from './common';
2022-11-12 21:15:41 +03:00
import { LoadVisits, VisitsInfo } from './types';
const REDUCER_PREFIX = 'shlink/orphanVisits';
export interface LoadOrphanVisits extends LoadVisits {
orphanVisitsType?: OrphanVisitType;
}
const initialState: VisitsInfo = {
visits: [],
loading: false,
loadingLarge: false,
error: false,
cancelLoad: false,
progress: 0,
};
2022-11-12 21:15:41 +03:00
const matchesType = (visit: OrphanVisit, orphanVisitsType?: OrphanVisitType) =>
!orphanVisitsType || orphanVisitsType === visit.type;
export const getOrphanVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => createVisitsAsyncThunk({
name: `${REDUCER_PREFIX}/getOrphanVisits`,
2022-11-12 21:15:41 +03:00
createLoaders: ({ orphanVisitsType, query = {}, doIntervalFallback = false }: LoadOrphanVisits, getState) => {
const { getOrphanVisits: getVisits } = buildShlinkApiClient(getState);
const visitsLoader = async (page: number, itemsPerPage: number) => getVisits({ ...query, page, itemsPerPage })
.then((result) => {
const visits = result.data.filter((visit) => isOrphanVisit(visit) && matchesType(visit, orphanVisitsType));
return { ...result, data: visits };
});
const lastVisitLoader = lastVisitLoaderForLoader(doIntervalFallback, getVisits);
2022-11-12 21:15:41 +03:00
return [visitsLoader, lastVisitLoader];
},
2022-11-12 21:15:41 +03:00
getExtraFulfilledPayload: ({ query = {} }: LoadOrphanVisits) => ({ query }),
shouldCancel: (getState) => getState().orphanVisits.cancelLoad,
});
2022-11-12 21:15:41 +03:00
export const orphanVisitsReducerCreator = (
getVisitsCreator: ReturnType<typeof getOrphanVisits>,
) => createVisitsReducer(
REDUCER_PREFIX,
getVisitsCreator,
initialState,
({ query = {} }, createdVisits) => {
const { startDate, endDate } = query;
return createdVisits.filter(({ visit, shortUrl }) => !shortUrl && isBetween(visit.date, startDate, endDate));
},
);