shlink-web-client/src/shlink-web-component/visits/reducers/domainVisits.ts

60 lines
2.1 KiB
TypeScript
Raw Normal View History

import type { ShlinkApiClientBuilder } from '../../../api/services/ShlinkApiClientBuilder';
import { isBetween } from '../../../utils/helpers/date';
2023-02-18 13:11:01 +03:00
import { domainMatches } from '../../short-urls/helpers';
import { createVisitsAsyncThunk, createVisitsReducer, lastVisitLoaderForLoader } from './common';
2023-02-18 12:40:37 +03:00
import type { LoadVisits, VisitsInfo } from './types';
2022-04-24 19:36:25 +03:00
const REDUCER_PREFIX = 'shlink/domainVisits';
2022-04-24 19:36:25 +03:00
export const DEFAULT_DOMAIN = 'DEFAULT';
interface WithDomain {
2022-04-24 19:36:25 +03:00
domain: string;
}
export interface DomainVisits extends VisitsInfo, WithDomain {}
export interface LoadDomainVisits extends LoadVisits, WithDomain {}
2022-04-24 19:36:25 +03:00
const initialState: DomainVisits = {
visits: [],
domain: '',
loading: false,
loadingLarge: false,
error: false,
cancelLoad: false,
progress: 0,
};
2022-11-12 19:51:37 +03:00
export const getDomainVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => createVisitsAsyncThunk({
typePrefix: `${REDUCER_PREFIX}/getDomainVisits`,
2022-11-12 19:51:37 +03:00
createLoaders: ({ domain, query = {}, doIntervalFallback = false }: LoadDomainVisits, getState) => {
const { getDomainVisits: getVisits } = buildShlinkApiClient(getState);
const visitsLoader = async (page: number, itemsPerPage: number) => getVisits(
domain,
{ ...query, page, itemsPerPage },
);
const lastVisitLoader = lastVisitLoaderForLoader(doIntervalFallback, async (params) => getVisits(domain, params));
2022-04-24 19:36:25 +03:00
2022-11-12 19:51:37 +03:00
return [visitsLoader, lastVisitLoader];
2022-04-24 19:36:25 +03:00
},
2022-11-12 19:51:37 +03:00
getExtraFulfilledPayload: ({ domain, query = {} }: LoadDomainVisits) => ({ domain, query }),
shouldCancel: (getState) => getState().domainVisits.cancelLoad,
});
2022-04-24 19:36:25 +03:00
2022-11-12 19:51:37 +03:00
export const domainVisitsReducerCreator = (
asyncThunkCreator: ReturnType<typeof getDomainVisits>,
) => createVisitsReducer({
name: REDUCER_PREFIX,
initialState,
// @ts-expect-error TODO Fix type inference
asyncThunkCreator,
filterCreatedVisits: ({ domain, query = {} }, createdVisits) => {
const { startDate, endDate } = query;
return createdVisits.filter(
({ shortUrl, visit }) =>
shortUrl && domainMatches(shortUrl, domain) && isBetween(visit.date, startDate, endDate),
);
},
});