All files / src/redux/utils createAsyncThunk.ts

0% Statements 0/342
100% Branches 0/0
0% Functions 0/1
0% Lines 0/342

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
/**
 * Async Thunk Utilities
 *
 * Standardized patterns for Redux Toolkit async thunks with:
 * - Typed error handling
 * - Consistent loading state management
 * - Reusable extra reducer builders
 */

import {
  createAsyncThunk as createAsyncThunkBase,
  ActionReducerMapBuilder,
  Draft,
  UnknownAction,
} from '@reduxjs/toolkit';
import type { RootState, AppDispatch } from '../store';

// ============================================================================
// TYPES
// ============================================================================

/**
 * Standard API error shape
 */
export interface ApiError {
  message: string;
  code?: string;
  status?: number;
  details?: unknown;
}

/**
 * Async thunk type for use with extra reducers
 */
export type AppAsyncThunk<Returned, ThunkArg> = ReturnType<
  typeof createAppAsyncThunk<Returned, ThunkArg>
>;

/**
 * Standard loading state shape
 * Add this to slice state interfaces that use async thunks
 */
export interface LoadingState {
  isLoading: boolean;
  isSuccess: boolean;
  isError: boolean;
  error: ApiError | null;
}

/**
 * Extended loading state with operation tracking
 */
export interface OperationLoadingState extends LoadingState {
  operationType: string | null;
  lastOperation: string | null;
  lastOperationTime: number | null;
}

// ============================================================================
// INITIAL STATES
// ============================================================================

/**
 * Initial loading state values
 */
export const initialLoadingState: LoadingState = {
  isLoading: false,
  isSuccess: false,
  isError: false,
  error: null,
};

/**
 * Initial operation loading state
 */
export const initialOperationLoadingState: OperationLoadingState = {
  ...initialLoadingState,
  operationType: null,
  lastOperation: null,
  lastOperationTime: null,
};

// ============================================================================
// ASYNC THUNK CREATOR
// ============================================================================

/**
 * Create a typed async thunk with standardized error handling
 *
 * @example
 * export const fetchProducts = createAppAsyncThunk(
 *   'products/fetch',
 *   async (filters: ProductFilters, { rejectWithValue }) => {
 *     const response = await fetch(`/api/products?${new URLSearchParams(filters)}`);
 *     if (!response.ok) {
 *       return rejectWithValue({ message: 'Failed to fetch products' });
 *     }
 *     return response.json();
 *   }
 * );
 */
export function createAppAsyncThunk<Returned, ThunkArg = void>(
  typePrefix: string,
  payloadCreator: (
    arg: ThunkArg,
    thunkApi: {
      dispatch: AppDispatch;
      getState: () => RootState;
      rejectWithValue: (value: ApiError) => ReturnType<typeof createAsyncThunkBase>['prototype']['rejected'];
    }
  ) => Promise<Returned>
) {
  return createAsyncThunkBase<Returned, ThunkArg, { state: RootState; dispatch: AppDispatch; rejectValue: ApiError }>(
    typePrefix,
    async (arg, thunkApi) => {
      try {
        return await payloadCreator(arg, {
          dispatch: thunkApi.dispatch,
          getState: thunkApi.getState,
          rejectWithValue: thunkApi.rejectWithValue,
        });
      } catch (error) {
        const apiError = normalizeError(error);
        return thunkApi.rejectWithValue(apiError);
      }
    }
  );
}

/**
 * Normalize various error types to ApiError
 */
function normalizeError(error: unknown): ApiError {
  if (error instanceof Error) {
    return {
      message: error.message,
      code: (error as { code?: string }).code,
      details: error,
    };
  }

  if (typeof error === 'object' && error !== null) {
    const errorObj = error as Record<string, unknown>;
    return {
      message: (errorObj.message as string) || 'An error occurred',
      code: errorObj.code as string | undefined,
      status: errorObj.status as number | undefined,
      details: errorObj.details,
    };
  }

  return {
    message: typeof error === 'string' ? error : 'An unknown error occurred',
  };
}

// ============================================================================
// EXTRA REDUCER BUILDERS
// ============================================================================

/**
 * Add standard loading state reducers for an async thunk
 *
 * @example
 * const slice = createSlice({
 *   name: 'products',
 *   initialState: { ...initialLoadingState, items: [] },
 *   reducers: {},
 *   extraReducers: (builder) => {
 *     addLoadingReducers(builder, fetchProducts);
 *     builder.addCase(fetchProducts.fulfilled, (state, action) => {
 *       state.items = action.payload;
 *     });
 *   },
 * });
 */
export function addLoadingReducers<State extends LoadingState>(
  builder: ActionReducerMapBuilder<State>,
  thunk: {
    pending: { type: string; match: (action: UnknownAction) => boolean };
    fulfilled: { type: string; match: (action: UnknownAction) => boolean };
    rejected: { type: string; match: (action: UnknownAction) => boolean };
  }
): void {
  builder
    .addMatcher(thunk.pending.match, (state) => {
      const s = state as Draft<LoadingState>;
      s.isLoading = true;
      s.isSuccess = false;
      s.isError = false;
      s.error = null;
    })
    .addMatcher(thunk.fulfilled.match, (state) => {
      const s = state as Draft<LoadingState>;
      s.isLoading = false;
      s.isSuccess = true;
    })
    .addMatcher(thunk.rejected.match, (state, action) => {
      const s = state as Draft<LoadingState>;
      s.isLoading = false;
      s.isError = true;
      const typedAction = action as { payload?: ApiError; error?: { message?: string } };
      s.error = typedAction.payload || {
        message: typedAction.error?.message || 'Unknown error',
      };
    });
}

/**
 * Add loading reducers with operation tracking
 */
export function addOperationLoadingReducers<State extends OperationLoadingState>(
  builder: ActionReducerMapBuilder<State>,
  thunk: {
    pending: { type: string; match: (action: UnknownAction) => boolean };
    fulfilled: { type: string; match: (action: UnknownAction) => boolean };
    rejected: { type: string; match: (action: UnknownAction) => boolean };
  },
  operationType: string
): void {
  builder
    .addMatcher(thunk.pending.match, (state) => {
      const s = state as Draft<OperationLoadingState>;
      s.isLoading = true;
      s.isSuccess = false;
      s.isError = false;
      s.error = null;
      s.operationType = operationType;
    })
    .addMatcher(thunk.fulfilled.match, (state) => {
      const s = state as Draft<OperationLoadingState>;
      s.isLoading = false;
      s.isSuccess = true;
      s.lastOperation = s.operationType;
      s.lastOperationTime = Date.now();
      s.operationType = null;
    })
    .addMatcher(thunk.rejected.match, (state, action) => {
      const s = state as Draft<OperationLoadingState>;
      s.isLoading = false;
      s.isError = true;
      const typedAction = action as { payload?: ApiError; error?: { message?: string } };
      s.error = typedAction.payload || {
        message: typedAction.error?.message || 'Unknown error',
      };
      s.lastOperation = s.operationType;
      s.lastOperationTime = Date.now();
      s.operationType = null;
    });
}

// ============================================================================
// UTILITY FUNCTIONS
// ============================================================================

/**
 * Async thunk action type helper
 */
type AsyncThunkActions = {
  pending: { match: (action: UnknownAction) => boolean };
  fulfilled: { match: (action: UnknownAction) => boolean };
  rejected: { match: (action: UnknownAction) => boolean };
};

/**
 * Create a matcher for all pending actions of given thunks
 */
export function isPendingAction(...thunks: AsyncThunkActions[]) {
  return (action: UnknownAction) =>
    thunks.some((thunk) => thunk.pending.match(action));
}

/**
 * Create a matcher for all fulfilled actions of given thunks
 */
export function isFulfilledAction(...thunks: AsyncThunkActions[]) {
  return (action: UnknownAction) =>
    thunks.some((thunk) => thunk.fulfilled.match(action));
}

/**
 * Create a matcher for all rejected actions of given thunks
 */
export function isRejectedAction(...thunks: AsyncThunkActions[]) {
  return (action: UnknownAction) =>
    thunks.some((thunk) => thunk.rejected.match(action));
}

/**
 * Check if an error is an API error with a specific code
 */
export function isApiErrorWithCode(error: unknown, code: string): boolean {
  return (
    typeof error === 'object' &&
    error !== null &&
    'code' in error &&
    (error as ApiError).code === code
  );
}

/**
 * Check if error indicates authentication required
 */
export function isAuthenticationError(error: unknown): boolean {
  if (!error || typeof error !== 'object') return false;
  const apiError = error as ApiError;
  return (
    apiError.status === 401 ||
    apiError.code === 'UNAUTHORIZED' ||
    apiError.code === 'LOGIN_REQUIRED'
  );
}

/**
 * Check if error indicates forbidden access
 */
export function isForbiddenError(error: unknown): boolean {
  if (!error || typeof error !== 'object') return false;
  const apiError = error as ApiError;
  return apiError.status === 403 || apiError.code === 'FORBIDDEN';
}

/**
 * Check if error indicates not found
 */
export function isNotFoundError(error: unknown): boolean {
  if (!error || typeof error !== 'object') return false;
  const apiError = error as ApiError;
  return apiError.status === 404 || apiError.code === 'NOT_FOUND';
}

/**
 * Get user-friendly error message
 */
export function getErrorMessage(error: unknown, fallback = 'An error occurred'): string {
  if (!error) return fallback;
  if (typeof error === 'string') return error;
  if (typeof error === 'object' && 'message' in error) {
    return (error as ApiError).message || fallback;
  }
  return fallback;
}