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

61 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';
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 { ProblemDetailsError } from '../../api/types/errors';
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;
2022-11-06 14:32:55 +03:00
saved: 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,
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: 'shortUrlEditionReducer',
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 };
};