shlink-web-client/src/short-urls/helpers/ExportShortUrlsBtn.tsx

63 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-02-18 12:40:37 +03:00
import type { FC } from 'react';
import type { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
2023-02-18 13:11:01 +03:00
import type { ReportExporter } from '../../common/services/ReportExporter';
2023-02-18 12:40:37 +03:00
import type { SelectedServer } from '../../servers/data';
import { isServerWithId } from '../../servers/data';
2023-02-18 13:11:01 +03:00
import { ExportBtn } from '../../utils/ExportBtn';
import { useToggle } from '../../utils/helpers/hooks';
2023-02-18 12:40:37 +03:00
import type { ShortUrl } from '../data';
2022-03-13 20:56:42 +03:00
import { useShortUrlsQuery } from './hooks';
export interface ExportShortUrlsBtnProps {
amount?: number;
}
interface ExportShortUrlsBtnConnectProps extends ExportShortUrlsBtnProps {
selectedServer: SelectedServer;
}
2022-03-17 22:28:47 +03:00
const itemsPerPage = 20;
2022-03-13 20:56:42 +03:00
export const ExportShortUrlsBtn = (
buildShlinkApiClient: ShlinkApiClientBuilder,
{ exportShortUrls }: ReportExporter,
): FC<ExportShortUrlsBtnConnectProps> => ({ amount = 0, selectedServer }) => {
const [{ tags, search, startDate, endDate, orderBy, tagsMode }] = useShortUrlsQuery();
2022-03-26 14:17:42 +03:00
const [loading,, startLoading, stopLoading] = useToggle();
2022-03-17 22:28:47 +03:00
const exportAllUrls = async () => {
2022-03-13 20:56:42 +03:00
if (!isServerWithId(selectedServer)) {
return;
}
const totalPages = amount / itemsPerPage;
const { listShortUrls } = buildShlinkApiClient(selectedServer);
const loadAllUrls = async (page = 1): Promise<ShortUrl[]> => {
const { data } = await listShortUrls(
{ page: `${page}`, tags, searchTerm: search, startDate, endDate, orderBy, tagsMode, itemsPerPage },
);
if (page >= totalPages) {
return data;
}
// TODO Support paralelization
return data.concat(await loadAllUrls(page + 1));
};
startLoading();
2022-03-17 22:28:47 +03:00
const shortUrls = await loadAllUrls();
exportShortUrls(shortUrls.map((shortUrl) => ({
createdAt: shortUrl.dateCreated,
shortUrl: shortUrl.shortUrl,
longUrl: shortUrl.longUrl,
title: shortUrl.title ?? '',
tags: shortUrl.tags.join(','),
visits: shortUrl?.visitsSummary?.total ?? shortUrl.visitsCount,
2022-03-17 22:28:47 +03:00
})));
stopLoading();
2022-03-13 20:56:42 +03:00
};
return <ExportBtn loading={loading} className="btn-md-block" amount={amount} onClick={exportAllUrls} />;
};