2022-11-06 14:32:55 +03:00
|
|
|
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
|
|
|
|
import { createAsyncThunk } from '../../utils/helpers/redux';
|
2022-11-06 21:12:41 +03:00
|
|
|
import { EditShortUrlData, ShortUrl, ShortUrlIdentifier } from '../data';
|
2020-12-22 11:55:39 +03:00
|
|
|
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
|
2020-12-22 11:24:33 +03:00
|
|
|
import { parseApiError } from '../../api/utils';
|
2022-10-12 11:35:16 +03:00
|
|
|
import { ProblemDetailsError } from '../../api/types/errors';
|
2020-03-30 21:42:58 +03:00
|
|
|
|
2022-11-09 20:19:07 +03:00
|
|
|
const REDUCER_PREFIX = 'shlink/shortUrlEdition';
|
|
|
|
export const SHORT_URL_EDITED = `${REDUCER_PREFIX}/editShortUrl`;
|
2020-03-30 21:42:58 +03:00
|
|
|
|
2020-08-26 19:55:40 +03:00
|
|
|
export interface ShortUrlEdition {
|
2021-03-27 15:56:44 +03:00
|
|
|
shortUrl?: ShortUrl;
|
2020-08-26 19:55:40 +03:00
|
|
|
saving: boolean;
|
2022-11-06 14:32:55 +03:00
|
|
|
saved: boolean;
|
2022-11-07 20:24:26 +03:00
|
|
|
error: boolean;
|
2020-12-21 23:26:45 +03:00
|
|
|
errorData?: ProblemDetailsError;
|
2020-08-26 19:55:40 +03:00
|
|
|
}
|
|
|
|
|
2022-11-06 21:12:41 +03:00
|
|
|
export interface EditShortUrl extends ShortUrlIdentifier {
|
2022-11-06 13:59:39 +03:00
|
|
|
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 = {
|
2020-03-30 21:42:58 +03:00
|
|
|
saving: false,
|
2022-11-06 14:32:55 +03:00
|
|
|
saved: false,
|
2020-03-30 21:42:58 +03:00
|
|
|
error: false,
|
|
|
|
};
|
|
|
|
|
2022-11-09 20:40:51 +03:00
|
|
|
export const editShortUrl = (buildShlinkApiClient: ShlinkApiClientBuilder) => createAsyncThunk(
|
|
|
|
SHORT_URL_EDITED,
|
|
|
|
({ shortCode, domain, data }: EditShortUrl, { getState }): Promise<ShortUrl> => {
|
|
|
|
const { updateShortUrl } = buildShlinkApiClient(getState);
|
|
|
|
return updateShortUrl(shortCode, domain, data as any); // FIXME parse dates
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
export const shortUrlEditionReducerCreator = (editShortUrlThunk: ReturnType<typeof editShortUrl>) => createSlice({
|
|
|
|
name: REDUCER_PREFIX,
|
|
|
|
initialState,
|
|
|
|
reducers: {},
|
|
|
|
extraReducers: (builder) => {
|
|
|
|
builder.addCase(editShortUrlThunk.pending, (state) => ({ ...state, saving: true, error: false, saved: false }));
|
|
|
|
builder.addCase(
|
|
|
|
editShortUrlThunk.rejected,
|
|
|
|
(state, { error }) => ({ ...state, saving: false, error: true, saved: false, errorData: parseApiError(error) }),
|
|
|
|
);
|
|
|
|
builder.addCase(
|
|
|
|
editShortUrlThunk.fulfilled,
|
|
|
|
(_, { payload: shortUrl }) => ({ shortUrl, saving: false, error: false, saved: true }),
|
|
|
|
);
|
|
|
|
},
|
|
|
|
}).reducer;
|