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

59 lines
2.1 KiB
TypeScript
Raw Normal View History

2022-11-06 13:53:23 +03:00
import { PayloadAction } from '@reduxjs/toolkit';
import { Dispatch } from 'redux';
2020-08-26 19:55:40 +03:00
import { buildReducer } from '../../utils/helpers/redux';
import { GetState } from '../../container/types';
2020-08-26 21:03:23 +03:00
import { OptionalString } from '../../utils/utils';
import { EditShortUrlData, ShortUrl } from '../data';
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
2020-12-22 11:24:33 +03:00
import { parseApiError } from '../../api/utils';
import { ApiErrorAction } from '../../api/types/actions';
import { ProblemDetailsError } from '../../api/types/errors';
export const EDIT_SHORT_URL_START = 'shlink/shortUrlEdition/EDIT_SHORT_URL_START';
export const EDIT_SHORT_URL_ERROR = 'shlink/shortUrlEdition/EDIT_SHORT_URL_ERROR';
export const SHORT_URL_EDITED = 'shlink/shortUrlEdition/SHORT_URL_EDITED';
2020-08-26 19:55:40 +03:00
export interface ShortUrlEdition {
shortUrl?: ShortUrl;
2020-08-26 19:55:40 +03:00
saving: boolean;
error: boolean;
errorData?: ProblemDetailsError;
2020-08-26 19:55:40 +03:00
}
export interface EditShortUrl {
shortCode: string;
domain?: OptionalString;
data: EditShortUrlData;
}
2022-11-06 13:53:23 +03:00
export type ShortUrlEditedAction = PayloadAction<ShortUrl>;
2020-08-26 19:55:40 +03:00
const initialState: ShortUrlEdition = {
saving: false,
error: false,
};
export default buildReducer<ShortUrlEdition, ShortUrlEditedAction & ApiErrorAction>({
[EDIT_SHORT_URL_START]: (state) => ({ ...state, saving: true, error: false }),
[EDIT_SHORT_URL_ERROR]: (state, { errorData }) => ({ ...state, saving: false, error: true, errorData }),
2022-11-06 13:53:23 +03:00
[SHORT_URL_EDITED]: (_, { payload: shortUrl }) => ({ shortUrl, saving: false, error: false }),
}, initialState);
2020-08-26 19:55:40 +03:00
export const editShortUrl = (buildShlinkApiClient: ShlinkApiClientBuilder) => (
{ shortCode, domain, data }: EditShortUrl,
2020-08-26 19:55:40 +03:00
) => async (dispatch: Dispatch, getState: GetState) => {
dispatch({ type: EDIT_SHORT_URL_START });
const { updateShortUrl } = buildShlinkApiClient(getState);
try {
2022-11-06 13:53:23 +03:00
const payload = await updateShortUrl(shortCode, domain, data as any); // FIXME parse dates;
2022-11-06 13:53:23 +03:00
dispatch<ShortUrlEditedAction>({ payload, type: SHORT_URL_EDITED });
} catch (e: any) {
dispatch<ApiErrorAction>({ type: EDIT_SHORT_URL_ERROR, errorData: parseApiError(e) });
throw e;
}
};