shlink-web-client/src/short-urls/helpers/hooks.ts

59 lines
2 KiB
TypeScript
Raw Normal View History

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';
import { isEmpty, pipe } from 'ramda';
2021-11-09 01:23:45 +03:00
import { parseQuery, stringifyQuery } from '../../utils/helpers/query';
import { ShortUrlsOrder, ShortUrlsOrderableFields } from '../data';
import { orderToString, stringToOrder } from '../../utils/helpers/ordering';
import { TagsFilteringMode } from '../../api/types';
2021-11-09 01:23:45 +03:00
interface ShortUrlsQueryCommon {
2021-11-09 01:23:45 +03:00
search?: string;
startDate?: string;
endDate?: string;
tagsMode?: TagsFilteringMode;
2021-11-09 01:23:45 +03:00
}
interface ShortUrlsQuery extends ShortUrlsQueryCommon {
orderBy?: string;
tags?: string;
}
interface ShortUrlsFiltering extends ShortUrlsQueryCommon {
orderBy?: ShortUrlsOrder;
tags: string[];
}
type ToFirstPage = (extra: Partial<ShortUrlsFiltering>) => void;
2022-02-06 22:07:18 +03:00
export const useShortUrlsQuery = (): [ShortUrlsFiltering, ToFirstPage] => {
const navigate = useNavigate();
const { search } = useLocation();
const { serverId = '' } = useParams<{ serverId: string }>();
2022-02-06 22:07:18 +03:00
const filtering = useMemo(
pipe(
() => parseQuery<ShortUrlsQuery>(search),
({ orderBy, tags, ...rest }: ShortUrlsQuery): ShortUrlsFiltering => {
const parsedOrderBy = orderBy ? stringToOrder<ShortUrlsOrderableFields>(orderBy) : undefined;
const parsedTags = tags?.split(',') ?? [];
return { ...rest, orderBy: parsedOrderBy, tags: parsedTags };
},
),
[search],
);
const toFirstPageWithExtra = (extra: Partial<ShortUrlsFiltering>) => {
const { orderBy, tags, ...mergedFiltering } = { ...filtering, ...extra };
const query: ShortUrlsQuery = {
...mergedFiltering,
orderBy: orderBy && orderToString(orderBy),
tags: tags.length > 0 ? tags.join(',') : undefined,
};
const stringifiedQuery = stringifyQuery(query);
const queryString = isEmpty(stringifiedQuery) ? '' : `?${stringifiedQuery}`;
2021-11-09 01:23:45 +03:00
navigate(`/server/${serverId}/list-short-urls/1${queryString}`);
2021-11-09 01:23:45 +03:00
};
return [filtering, toFirstPageWithExtra];
2021-11-09 01:23:45 +03:00
};