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

60 lines
2 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 { 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,
};
export const getDomainVisits = (apiClientFactory: () => ShlinkApiClient) => createVisitsAsyncThunk({
typePrefix: `${REDUCER_PREFIX}/getDomainVisits`,
createLoaders: ({ domain, query = {}, doIntervalFallback = false }: LoadDomainVisits) => {
const { getDomainVisits: getVisits } = apiClientFactory();
2022-11-12 19:51:37 +03:00
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),
);
},
});