2023-02-18 12:40:37 +03:00
|
|
|
import type { PayloadAction } from '@reduxjs/toolkit';
|
|
|
|
import { createSlice } from '@reduxjs/toolkit';
|
|
|
|
import type { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
|
|
|
|
import type { ProblemDetailsError } from '../../api/types/errors';
|
2023-02-18 13:11:01 +03:00
|
|
|
import { parseApiError } from '../../api/utils';
|
|
|
|
import { createAsyncThunk } from '../../utils/helpers/redux';
|
|
|
|
import type { EditShortUrlData, ShortUrl, ShortUrlIdentifier } from '../data';
|
2020-03-30 21:42:58 +03:00
|
|
|
|
2022-11-09 20:19:07 +03:00
|
|
|
const REDUCER_PREFIX = 'shlink/shortUrlEdition';
|
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(
|
2022-11-09 21:13:44 +03:00
|
|
|
`${REDUCER_PREFIX}/editShortUrl`,
|
2022-11-09 20:40:51 +03:00
|
|
|
({ 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 }),
|
|
|
|
);
|
|
|
|
},
|
2022-11-09 21:13:44 +03:00
|
|
|
});
|