2023-02-18 12:40:37 +03:00
|
|
|
import type { FC } from 'react';
|
2023-04-21 10:36:51 +03:00
|
|
|
import { useCallback } from 'react';
|
2023-07-24 18:30:58 +03:00
|
|
|
import type { ShlinkApiClient } from '../../api-contract';
|
2023-07-29 11:43:15 +03:00
|
|
|
import { ExportBtn } from '../../utils/components/ExportBtn';
|
2023-07-27 23:23:46 +03:00
|
|
|
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 = (
|
2023-07-26 21:04:50 +03:00
|
|
|
apiClientFactory: () => ShlinkApiClient,
|
2022-03-13 20:56:42 +03:00
|
|
|
{ exportShortUrls }: ReportExporter,
|
2023-07-24 19:03:59 +03:00
|
|
|
): 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();
|
2023-04-21 10:36:51 +03:00
|
|
|
const exportAllUrls = useCallback(async () => {
|
2022-03-13 20:56:42 +03:00
|
|
|
const totalPages = amount / itemsPerPage;
|
|
|
|
const loadAllUrls = async (page = 1): Promise<ShortUrl[]> => {
|
2023-07-26 21:04:50 +03:00
|
|
|
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();
|
|
|
|
|
2023-04-21 10:36:51 +03:00
|
|
|
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();
|
2023-07-24 19:03:59 +03:00
|
|
|
}, []);
|
2022-03-13 20:56:42 +03:00
|
|
|
|
|
|
|
return <ExportBtn loading={loading} className="btn-md-block" amount={amount} onClick={exportAllUrls} />;
|
|
|
|
};
|