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

59 lines
1.9 KiB
TypeScript
Raw Normal View History

import { createAction, createSlice } from '@reduxjs/toolkit';
2023-07-24 18:30:58 +03:00
import type { ProblemDetailsError, ShlinkApiClient } from '../../api-contract';
import { parseApiError } from '../../api-contract/utils';
import { createAsyncThunk } from '../../utils/redux';
2023-02-18 12:40:37 +03:00
import type { ShortUrl, ShortUrlIdentifier } from '../data';
2018-09-16 11:47:17 +03:00
const REDUCER_PREFIX = 'shlink/shortUrlDeletion';
2018-09-16 11:47:17 +03:00
2020-08-26 19:55:40 +03:00
export interface ShortUrlDeletion {
shortCode: string;
loading: boolean;
deleted: boolean;
2020-08-26 19:55:40 +03:00
error: boolean;
errorData?: ProblemDetailsError;
}
const initialState: ShortUrlDeletion = {
2018-09-16 11:47:17 +03:00
shortCode: '',
loading: false,
deleted: false,
2018-09-16 11:47:17 +03:00
error: false,
};
export const deleteShortUrl = (apiClientFactory: () => ShlinkApiClient) => createAsyncThunk(
2022-11-09 21:13:44 +03:00
`${REDUCER_PREFIX}/deleteShortUrl`,
async ({ shortCode, domain }: ShortUrlIdentifier): Promise<ShortUrlIdentifier> => {
await apiClientFactory().deleteShortUrl(shortCode, domain);
2022-11-09 21:13:44 +03:00
return { shortCode, domain };
},
);
export const shortUrlDeleted = createAction<ShortUrl>(`${REDUCER_PREFIX}/shortUrlDeleted`);
2022-11-09 21:13:44 +03:00
export const shortUrlDeletionReducerCreator = (deleteShortUrlThunk: ReturnType<typeof deleteShortUrl>) => {
const { actions, reducer } = createSlice({
name: REDUCER_PREFIX,
initialState,
reducers: {
resetDeleteShortUrl: () => initialState,
},
extraReducers: (builder) => {
2022-11-09 21:13:44 +03:00
builder.addCase(
deleteShortUrlThunk.pending,
(state) => ({ ...state, loading: true, error: false, deleted: false }),
);
builder.addCase(deleteShortUrlThunk.rejected, (state, { error }) => (
{ ...state, errorData: parseApiError(error), loading: false, error: true, deleted: false }
));
2022-11-09 21:13:44 +03:00
builder.addCase(deleteShortUrlThunk.fulfilled, (state, { payload }) => (
{ ...state, shortCode: payload.shortCode, loading: false, error: false, deleted: true }
));
},
});
const { resetDeleteShortUrl } = actions;
2022-11-09 21:13:44 +03:00
return { reducer, resetDeleteShortUrl };
2018-09-16 11:47:17 +03:00
};