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

53 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-02-18 12:40:37 +03:00
import type { PayloadAction } from '@reduxjs/toolkit';
import { createSlice } from '@reduxjs/toolkit';
import { createAsyncThunk } from '../../../src/utils/helpers/redux';
2023-07-24 18:30:58 +03:00
import type { ProblemDetailsError, ShlinkApiClient } from '../../api-contract';
import { parseApiError } from '../../api-contract/utils';
2023-02-18 13:11:01 +03:00
import type { EditShortUrlData, ShortUrl, ShortUrlIdentifier } from '../data';
const REDUCER_PREFIX = 'shlink/shortUrlEdition';
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,
};
export const editShortUrl = (apiClient: ShlinkApiClient) => createAsyncThunk(
2022-11-09 21:13:44 +03:00
`${REDUCER_PREFIX}/editShortUrl`,
({ shortCode, domain, data }: EditShortUrl): Promise<ShortUrl> =>
apiClient.updateShortUrl(shortCode, domain, data as any) // TODO 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
});