2023-02-18 12:40:37 +03:00
|
|
|
import type { PayloadAction } from '@reduxjs/toolkit';
|
|
|
|
import { createSlice } from '@reduxjs/toolkit';
|
2023-07-24 21:14:59 +03:00
|
|
|
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 { ShortUrl, ShortUrlIdentifier } from '../data';
|
|
|
|
import { shortUrlMatches } from '../helpers';
|
2020-08-28 19:33:37 +03:00
|
|
|
|
2022-11-09 20:19:07 +03:00
|
|
|
const REDUCER_PREFIX = 'shlink/shortUrlDetail';
|
2020-08-28 19:33:37 +03:00
|
|
|
|
|
|
|
export interface ShortUrlDetail {
|
|
|
|
shortUrl?: ShortUrl;
|
|
|
|
loading: boolean;
|
|
|
|
error: boolean;
|
2021-03-20 18:32:12 +03:00
|
|
|
errorData?: ProblemDetailsError;
|
2020-08-28 19:33:37 +03:00
|
|
|
}
|
|
|
|
|
2022-11-06 21:06:39 +03:00
|
|
|
export type ShortUrlDetailAction = PayloadAction<ShortUrl>;
|
2020-08-28 19:33:37 +03:00
|
|
|
|
|
|
|
const initialState: ShortUrlDetail = {
|
|
|
|
loading: false,
|
|
|
|
error: false,
|
|
|
|
};
|
|
|
|
|
2023-07-24 10:48:41 +03:00
|
|
|
export const shortUrlDetailReducerCreator = (apiClient: ShlinkApiClient) => {
|
2022-11-06 21:32:02 +03:00
|
|
|
const getShortUrlDetail = createAsyncThunk(
|
2022-11-09 20:19:07 +03:00
|
|
|
`${REDUCER_PREFIX}/getShortUrlDetail`,
|
2022-11-06 21:32:02 +03:00
|
|
|
async ({ shortCode, domain }: ShortUrlIdentifier, { getState }): Promise<ShortUrl> => {
|
|
|
|
const { shortUrlsList } = getState();
|
|
|
|
const alreadyLoaded = shortUrlsList?.shortUrls?.data.find((url) => shortUrlMatches(url, shortCode, domain));
|
|
|
|
|
2023-07-24 10:48:41 +03:00
|
|
|
return alreadyLoaded ?? await apiClient.getShortUrl(shortCode, domain);
|
2022-11-06 21:32:02 +03:00
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
const { reducer } = createSlice({
|
2022-11-09 20:19:07 +03:00
|
|
|
name: REDUCER_PREFIX,
|
2022-11-06 21:32:02 +03:00
|
|
|
initialState,
|
|
|
|
reducers: {},
|
|
|
|
extraReducers: (builder) => {
|
|
|
|
builder.addCase(getShortUrlDetail.pending, () => ({ loading: true, error: false }));
|
|
|
|
builder.addCase(getShortUrlDetail.rejected, (_, { error }) => (
|
|
|
|
{ loading: false, error: true, errorData: parseApiError(error) }
|
|
|
|
));
|
|
|
|
builder.addCase(getShortUrlDetail.fulfilled, (_, { payload: shortUrl }) => ({ ...initialState, shortUrl }));
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
return { reducer, getShortUrlDetail };
|
2020-08-28 19:33:37 +03:00
|
|
|
};
|