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

54 lines
2.1 KiB
TypeScript
Raw Normal View History

import { isBetween } from '../../../src/utils/helpers/date';
2023-07-24 18:30:58 +03:00
import type { ShlinkApiClient } from '../../api-contract';
2023-02-18 13:11:01 +03:00
import type { OrphanVisit, OrphanVisitType } from '../types';
import { isOrphanVisit } from '../types/helpers';
import { createVisitsAsyncThunk, createVisitsReducer, lastVisitLoaderForLoader } from './common';
2023-02-18 12:40:37 +03:00
import type { 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 = (apiClientFactory: () => ShlinkApiClient) => createVisitsAsyncThunk({
typePrefix: `${REDUCER_PREFIX}/getOrphanVisits`,
createLoaders: ({ orphanVisitsType, query = {}, doIntervalFallback = false }: LoadOrphanVisits) => {
const { getOrphanVisits: getVisits } = apiClientFactory();
2022-11-12 21:15:41 +03:00
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 = (
asyncThunkCreator: ReturnType<typeof getOrphanVisits>,
) => createVisitsReducer({
name: REDUCER_PREFIX,
initialState,
asyncThunkCreator,
filterCreatedVisits: ({ query = {} }, createdVisits) => {
const { startDate, endDate } = query;
return createdVisits.filter(({ visit, shortUrl }) => !shortUrl && isBetween(visit.date, startDate, endDate));
},
});