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

55 lines
1.9 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 type { ShlinkApiClientBuilder } from '../../../api/services/ShlinkApiClientBuilder';
import type { ProblemDetailsError } from '../../../api/types/errors';
import { parseApiError } from '../../../api/utils';
import { createAsyncThunk } from '../../../utils/helpers/redux';
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 = (buildShlinkApiClient: ShlinkApiClientBuilder) => createAsyncThunk(
2022-11-09 21:13:44 +03:00
`${REDUCER_PREFIX}/editShortUrl`,
({ 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
});