2022-11-06 21:32:02 +03:00
|
|
|
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
|
2022-11-06 21:16:51 +03:00
|
|
|
import { ShortUrl, ShortUrlIdentifier } from '../data';
|
2022-11-06 21:32:02 +03:00
|
|
|
import { createAsyncThunk } from '../../utils/helpers/redux';
|
2020-12-22 11:55:39 +03:00
|
|
|
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
|
2021-03-05 18:25:20 +03:00
|
|
|
import { shortUrlMatches } from '../helpers';
|
2021-03-20 18:32:12 +03:00
|
|
|
import { parseApiError } from '../../api/utils';
|
2022-10-12 11:35:16 +03:00
|
|
|
import { ProblemDetailsError } from '../../api/types/errors';
|
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,
|
|
|
|
};
|
|
|
|
|
2022-11-06 21:32:02 +03:00
|
|
|
export const shortUrlDetailReducerCreator = (buildShlinkApiClient: ShlinkApiClientBuilder) => {
|
|
|
|
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));
|
|
|
|
|
|
|
|
return alreadyLoaded ?? await buildShlinkApiClient(getState).getShortUrl(shortCode, domain);
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
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
|
|
|
};
|