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

63 lines
2.4 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 type { ShortUrlIdentifier } from '../../short-urls/data';
import { shortUrlMatches } from '../../short-urls/helpers';
import { createVisitsAsyncThunk, createVisitsReducer, lastVisitLoaderForLoader } from './common';
2023-02-18 12:40:37 +03:00
import type { LoadVisits, VisitsInfo } from './types';
2018-07-29 20:25:22 +03:00
const REDUCER_PREFIX = 'shlink/shortUrlVisits';
2018-07-29 20:25:22 +03:00
export interface ShortUrlVisits extends VisitsInfo, ShortUrlIdentifier {}
export interface LoadShortUrlVisits extends LoadVisits {
shortCode: string;
}
const initialState: ShortUrlVisits = {
2018-07-29 20:25:22 +03:00
visits: [],
shortCode: '',
domain: undefined, // Deprecated. Value from query params can be used instead
2018-07-29 20:25:22 +03:00
loading: false,
loadingLarge: false,
error: false,
cancelLoad: false,
progress: 0,
2018-07-29 20:25:22 +03:00
};
2022-11-12 21:36:12 +03:00
export const getShortUrlVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => createVisitsAsyncThunk({
typePrefix: `${REDUCER_PREFIX}/getShortUrlVisits`,
2022-11-12 21:36:12 +03:00
createLoaders: ({ shortCode, query = {}, doIntervalFallback = false }: LoadShortUrlVisits, getState) => {
const { getShortUrlVisits: shlinkGetShortUrlVisits } = buildShlinkApiClient(getState);
const visitsLoader = async (page: number, itemsPerPage: number) => shlinkGetShortUrlVisits(
shortCode,
{ ...query, page, itemsPerPage },
);
const lastVisitLoader = lastVisitLoaderForLoader(
doIntervalFallback,
async (params) => shlinkGetShortUrlVisits(shortCode, { ...params, domain: query.domain }),
);
2022-11-12 21:36:12 +03:00
return [visitsLoader, lastVisitLoader];
},
2022-11-12 21:36:12 +03:00
getExtraFulfilledPayload: ({ shortCode, query = {} }: LoadShortUrlVisits) => (
{ shortCode, query, domain: query.domain }
),
shouldCancel: (getState) => getState().shortUrlVisits.cancelLoad,
});
2018-07-29 20:25:22 +03:00
2022-11-12 21:36:12 +03:00
export const shortUrlVisitsReducerCreator = (
asyncThunkCreator: ReturnType<typeof getShortUrlVisits>,
) => createVisitsReducer({
name: REDUCER_PREFIX,
initialState,
// @ts-expect-error TODO Fix type inference
asyncThunkCreator,
filterCreatedVisits: ({ shortCode, domain, query = {} }: ShortUrlVisits, createdVisits) => {
const { startDate, endDate } = query;
return createdVisits.filter(
({ shortUrl, visit }) =>
shortUrl && shortUrlMatches(shortUrl, shortCode, domain) && isBetween(visit.date, startDate, endDate),
);
},
});