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

70 lines
2.3 KiB
TypeScript
Raw Normal View History

2023-02-18 12:40:37 +03:00
import type { FC } from 'react';
import { useCallback } from 'react';
import type { ShlinkApiClient } from '../../../api/services/ShlinkApiClient';
import type { ReportExporter } from '../../../common/services/ReportExporter';
import type { SelectedServer } from '../../../servers/data';
import { isServerWithId } from '../../../servers/data';
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 = (
apiClient: ShlinkApiClient,
2022-03-13 20:56:42 +03:00
{ 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();
const exportAllUrls = useCallback(async () => {
2022-03-13 20:56:42 +03:00
if (!isServerWithId(selectedServer)) {
return;
}
const totalPages = amount / itemsPerPage;
const loadAllUrls = async (page = 1): Promise<ShortUrl[]> => {
const { data } = await apiClient.listShortUrls(
2022-03-13 20:56:42 +03:00
{ 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) => {
const { hostname: domain, pathname } = new URL(shortUrl.shortUrl);
const shortCode = pathname.substring(1); // Remove trailing slash
return {
createdAt: shortUrl.dateCreated,
domain,
shortCode,
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();
}, [selectedServer]);
2022-03-13 20:56:42 +03:00
return <ExportBtn loading={loading} className="btn-md-block" amount={amount} onClick={exportAllUrls} />;
};