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

59 lines
1.9 KiB
TypeScript
Raw Normal View History

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';
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
2020-12-22 11:24:33 +03:00
import { parseApiError } from '../../api/utils';
import { ProblemDetailsError } from '../../api/types/errors';
const REDUCER_PREFIX = 'shlink/shortUrlEdition';
export const SHORT_URL_EDITED = `${REDUCER_PREFIX}/editShortUrl`;
2020-08-26 19:55:40 +03:00
export interface ShortUrlEdition {
shortUrl?: ShortUrl;
2020-08-26 19:55:40 +03:00
saving: boolean;
2022-11-06 14:32:55 +03:00
saved: boolean;
error: boolean;
errorData?: ProblemDetailsError;
2020-08-26 19:55:40 +03:00
}
2022-11-06 21:12:41 +03:00
export interface EditShortUrl extends ShortUrlIdentifier {
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,
2022-11-06 14:32:55 +03:00
saved: false,
error: false,
};
2022-11-06 14:32:55 +03:00
export const shortUrlEditionReducerCreator = (buildShlinkApiClient: ShlinkApiClientBuilder) => {
const editShortUrl = 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
},
);
const { reducer } = createSlice({
name: REDUCER_PREFIX,
2022-11-06 14:32:55 +03:00
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(editShortUrl.pending, (state) => ({ ...state, saving: true, error: false, saved: false }));
builder.addCase(
editShortUrl.rejected,
(state, { error }) => ({ ...state, saving: false, error: true, saved: false, errorData: parseApiError(error) }),
);
builder.addCase(
editShortUrl.fulfilled,
(_, { payload: shortUrl }) => ({ shortUrl, saving: false, error: false, saved: true }),
);
},
});
return { reducer, editShortUrl };
};