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

60 lines
2 KiB
TypeScript
Raw Normal View History

2023-02-18 12:40:37 +03:00
import type { FC } from 'react';
import { useCallback } from 'react';
2023-07-24 18:30:58 +03:00
import type { ShlinkApiClient } from '../../api-contract';
import { ExportBtn } from '../../utils/components/ExportBtn';
import { useToggle } from '../../utils/helpers/hooks';
import type { ReportExporter } from '../../utils/services/ReportExporter';
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;
}
2022-03-17 22:28:47 +03:00
const itemsPerPage = 20;
2022-03-13 20:56:42 +03:00
export const ExportShortUrlsBtn = (
apiClientFactory: () => ShlinkApiClient,
2022-03-13 20:56:42 +03:00
{ exportShortUrls }: ReportExporter,
): FC<ExportShortUrlsBtnProps> => ({ amount = 0 }) => {
2022-03-13 20:56:42 +03:00
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
const totalPages = amount / itemsPerPage;
const loadAllUrls = async (page = 1): Promise<ShortUrl[]> => {
const { data } = await apiClientFactory().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();
}, []);
2022-03-13 20:56:42 +03:00
return <ExportBtn loading={loading} className="btn-md-block" amount={amount} onClick={exportAllUrls} />;
};