shlink-web-client/src/short-urls/reducers/shortUrlDetail.ts

60 lines
2.3 KiB
TypeScript
Raw Normal View History

import { Action, Dispatch } from 'redux';
import { ShortUrl } from '../data';
import { buildReducer } from '../../utils/helpers/redux';
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
import { OptionalString } from '../../utils/utils';
import { GetState } from '../../container/types';
import { shortUrlMatches } from '../helpers';
2021-03-20 18:32:12 +03:00
import { ProblemDetailsError } from '../../api/types';
import { parseApiError } from '../../api/utils';
/* eslint-disable padding-line-between-statements */
export const GET_SHORT_URL_DETAIL_START = 'shlink/shortUrlDetail/GET_SHORT_URL_DETAIL_START';
export const GET_SHORT_URL_DETAIL_ERROR = 'shlink/shortUrlDetail/GET_SHORT_URL_DETAIL_ERROR';
export const GET_SHORT_URL_DETAIL = 'shlink/shortUrlDetail/GET_SHORT_URL_DETAIL';
/* eslint-enable padding-line-between-statements */
export interface ShortUrlDetail {
shortUrl?: ShortUrl;
loading: boolean;
error: boolean;
2021-03-20 18:32:12 +03:00
errorData?: ProblemDetailsError;
}
export interface ShortUrlDetailAction extends Action<string> {
shortUrl: ShortUrl;
}
2021-03-20 18:32:12 +03:00
export interface ShortUrlDetailFailedAction extends Action<string> {
errorData?: ProblemDetailsError;
}
const initialState: ShortUrlDetail = {
loading: false,
error: false,
};
2021-03-20 18:32:12 +03:00
export default buildReducer<ShortUrlDetail, ShortUrlDetailAction & ShortUrlDetailFailedAction>({
[GET_SHORT_URL_DETAIL_START]: () => ({ loading: true, error: false }),
2021-03-20 18:32:12 +03:00
[GET_SHORT_URL_DETAIL_ERROR]: (_, { errorData }) => ({ loading: false, error: true, errorData }),
[GET_SHORT_URL_DETAIL]: (_, { shortUrl }) => ({ shortUrl, ...initialState }),
}, initialState);
export const getShortUrlDetail = (buildShlinkApiClient: ShlinkApiClientBuilder) => (
shortCode: string,
domain: OptionalString,
) => async (dispatch: Dispatch, getState: GetState) => {
dispatch({ type: GET_SHORT_URL_DETAIL_START });
try {
const { shortUrlsList } = getState();
const shortUrl = shortUrlsList?.shortUrls?.data.find(
(shortUrl) => shortUrlMatches(shortUrl, shortCode, domain),
) ?? await buildShlinkApiClient(getState).getShortUrl(shortCode, domain);
dispatch<ShortUrlDetailAction>({ shortUrl, type: GET_SHORT_URL_DETAIL });
} catch (e) {
2021-03-20 18:32:12 +03:00
dispatch<ShortUrlDetailFailedAction>({ type: GET_SHORT_URL_DETAIL_ERROR, errorData: parseApiError(e) });
}
};