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

63 lines
2.3 KiB
TypeScript
Raw Normal View History

import { shortUrlMatches } from '../../short-urls/helpers';
import { ShortUrlIdentifier } from '../../short-urls/data';
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
import { isBetween } from '../../utils/helpers/date';
import { createVisitsAsyncThunk, createVisitsReducer, lastVisitLoaderForLoader } from './common';
2022-11-12 21:36:12 +03:00
import { 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({
name: `${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 = (
getVisitsCreator: ReturnType<typeof getShortUrlVisits>,
) => createVisitsReducer(
REDUCER_PREFIX,
// @ts-expect-error TODO Fix type inference
getVisitsCreator,
initialState,
({ shortCode, domain, query = {} }, createdVisits) => {
const { startDate, endDate } = query;
return createdVisits.filter(
({ shortUrl, visit }) =>
shortUrl && shortUrlMatches(shortUrl, shortCode, domain) && isBetween(visit.date, startDate, endDate),
);
},
);