2022-02-06 22:07:18 +03:00
|
|
|
import { useParams, useLocation, useNavigate } from 'react-router-dom';
|
2021-11-09 01:23:45 +03:00
|
|
|
import { useMemo } from 'react';
|
2021-12-25 21:51:25 +03:00
|
|
|
import { isEmpty, pipe } from 'ramda';
|
2021-11-09 01:23:45 +03:00
|
|
|
import { parseQuery, stringifyQuery } from '../../utils/helpers/query';
|
2021-12-25 21:51:25 +03:00
|
|
|
import { ShortUrlsOrder, ShortUrlsOrderableFields } from '../data';
|
|
|
|
import { orderToString, stringToOrder } from '../../utils/helpers/ordering';
|
2022-01-31 12:15:25 +03:00
|
|
|
import { TagsFilteringMode } from '../../api/types';
|
2021-11-09 01:23:45 +03:00
|
|
|
|
2021-12-25 21:51:25 +03:00
|
|
|
type ToFirstPage = (extra: Partial<ShortUrlsFiltering>) => void;
|
2021-11-09 01:23:45 +03:00
|
|
|
|
|
|
|
export interface ShortUrlListRouteParams {
|
|
|
|
page: string;
|
|
|
|
serverId: string;
|
|
|
|
}
|
|
|
|
|
2021-12-25 21:51:25 +03:00
|
|
|
interface ShortUrlsQueryCommon {
|
2021-11-09 01:23:45 +03:00
|
|
|
tags?: string;
|
|
|
|
search?: string;
|
2021-11-11 00:25:56 +03:00
|
|
|
startDate?: string;
|
|
|
|
endDate?: string;
|
2022-01-31 12:15:25 +03:00
|
|
|
tagsMode?: TagsFilteringMode;
|
2021-11-09 01:23:45 +03:00
|
|
|
}
|
|
|
|
|
2021-12-25 21:51:25 +03:00
|
|
|
interface ShortUrlsQuery extends ShortUrlsQueryCommon {
|
|
|
|
orderBy?: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
interface ShortUrlsFiltering extends ShortUrlsQueryCommon {
|
|
|
|
orderBy?: ShortUrlsOrder;
|
|
|
|
}
|
|
|
|
|
2022-02-06 22:07:18 +03:00
|
|
|
export const useShortUrlsQuery = (): [ShortUrlsFiltering, ToFirstPage] => {
|
|
|
|
const navigate = useNavigate();
|
|
|
|
const location = useLocation();
|
|
|
|
const params = useParams<{ serverId: string }>();
|
|
|
|
|
2021-12-25 21:51:25 +03:00
|
|
|
const query = useMemo(
|
|
|
|
pipe(
|
|
|
|
() => parseQuery<ShortUrlsQuery>(location.search),
|
|
|
|
({ orderBy, ...rest }: ShortUrlsQuery): ShortUrlsFiltering => !orderBy ? rest : {
|
|
|
|
...rest,
|
|
|
|
orderBy: stringToOrder<ShortUrlsOrderableFields>(orderBy),
|
|
|
|
},
|
|
|
|
),
|
|
|
|
[ location.search ],
|
|
|
|
);
|
|
|
|
const toFirstPageWithExtra = (extra: Partial<ShortUrlsFiltering>) => {
|
|
|
|
const { orderBy, ...mergedQuery } = { ...query, ...extra };
|
|
|
|
const normalizedQuery: ShortUrlsQuery = { ...mergedQuery, orderBy: orderBy && orderToString(orderBy) };
|
|
|
|
const evolvedQuery = stringifyQuery(normalizedQuery);
|
2021-11-09 01:23:45 +03:00
|
|
|
const queryString = isEmpty(evolvedQuery) ? '' : `?${evolvedQuery}`;
|
|
|
|
|
2022-02-06 22:07:18 +03:00
|
|
|
navigate(`/server/${params.serverId}/list-short-urls/1${queryString}`);
|
2021-11-09 01:23:45 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
return [ query, toFirstPageWithExtra ];
|
|
|
|
};
|