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 | 56x 56x 56x 56x 56x 56x 56x 56x 2x 2x 56x 56x 1x 56x 14x 14x 56x 2x 2x 56x 13x 13x 56x 280x 280x 13x 13x 56x 56x 56x 56x 56x 56x 280x 56x 280x 2x 2x 4x 2x 4x 2x 2x 2x 56x | import {
type AsyncThunk,
createAsyncThunk,
createEntityAdapter,
createSelector,
createSlice,
type Draft,
} from '@reduxjs/toolkit';
import {
CRUD_ACTION_SUFFIXES,
ENTITY_LOADING_STATUSES,
type EntityLoadingStatus,
PROJECT_MESSAGES,
} from '@/shared/constants';
import { createThunkWithErrorHandling } from '@/shared/lib/store';
/**
* Generic CRUD slice factory with strict type safety.
*
* @template T - Entity type (must include `id: string`)
* @template C - Argument type for createOne (defaults to Partial<T>)
* @template U - Argument type for updateOne (Partial<T> & { id: string })
* @template P - Argument type for fetchByParam (e.g., projectId)
*/
export function createAsyncEntitySlice<
T extends { id: string; name?: string },
C = Partial<T>,
U = Partial<T> & { id: string },
P = void,
>(options: {
name: string;
fetchAll?: () => Promise<T[]>;
fetchByParam?: (param: P) => Promise<T[]>;
createOne: (data: C) => Promise<T>;
updateOne: (data: U) => Promise<T>;
deleteOne: (id: string) => Promise<string>;
sortComparer?: (a: T, b: T) => number;
}) {
const {
name,
fetchAll,
fetchByParam,
createOne,
updateOne,
deleteOne,
sortComparer,
} = options;
const adapter = createEntityAdapter<T>({ sortComparer });
// Helper: creates a noop thunk that always resolves with empty array
const noopThunk = createAsyncThunk(`${name}/noop`, async () => [] as T[]);
// ──────────────────────────────
// Async Thunks
// ──────────────────────────────
const fetchAllThunk = fetchAll
? createThunkWithErrorHandling<T[], void>(
`${name}${CRUD_ACTION_SUFFIXES.FETCH_ALL}`,
fetchAll,
)
: (noopThunk as unknown as AsyncThunk<T[], void, { rejectValue: string }>);
const fetchByParamThunk = fetchByParam
? createThunkWithErrorHandling<{ param: P; data: T[] }, P>(
`${name}${CRUD_ACTION_SUFFIXES.FETCH_BY_PARAM}`,
async (param) => {
const data = await fetchByParam(param);
return { param, data };
},
)
: (noopThunk as unknown as AsyncThunk<
{ param: P; data: T[] },
P,
{ rejectValue: string }
>);
const createOneThunk = createThunkWithErrorHandling<T, C>(
`${name}${CRUD_ACTION_SUFFIXES.CREATE_ONE}`,
createOne,
);
const updateOneThunk = createThunkWithErrorHandling<T, U>(
`${name}${CRUD_ACTION_SUFFIXES.UPDATE_ONE}`,
updateOne,
);
const deleteOneThunk = createThunkWithErrorHandling<string, string>(
`${name}${CRUD_ACTION_SUFFIXES.DELETE_ONE}`,
async (id) => {
await deleteOne(id);
return id;
},
);
// ──────────────────────────────
// Initial State
// ──────────────────────────────
const initialState = adapter.getInitialState({
loading: ENTITY_LOADING_STATUSES.IDLE as EntityLoadingStatus,
error: null as string | null,
});
type SliceState = typeof initialState;
// ──────────────────────────────
// Slice Definition
// ──────────────────────────────
const slice = createSlice({
name,
initialState,
reducers: {
clearError(state) {
state.error = null;
},
reset: () => initialState,
},
extraReducers: (builder) => {
const handlePending = (state: Draft<SliceState>) => {
state.loading = ENTITY_LOADING_STATUSES.PENDING;
state.error = null;
};
const handleRejected = (
state: Draft<SliceState>,
action: { payload?: string; error: { message?: string } },
) => {
state.loading = ENTITY_LOADING_STATUSES.FAILED;
state.error =
action.payload ??
action.error.message ??
PROJECT_MESSAGES.ERROR_ACTION;
};
const handleFulfilled = (state: Draft<SliceState>) => {
state.loading = ENTITY_LOADING_STATUSES.SUCCEEDED;
state.error = null;
};
const addFulfilled = <R, A>(
thunk: AsyncThunk<R, A, { rejectValue: string }> | undefined,
handler: (state: Draft<SliceState>, payload: R) => void,
): void => {
Eif (thunk) {
builder.addCase(thunk.fulfilled, (state, action) => {
handler(state, action.payload);
handleFulfilled(state);
});
}
};
// Fulfilled cases
addFulfilled(fetchAllThunk, (s, p) => adapter.setAll(s, p));
addFulfilled(fetchByParamThunk, (s, p) => adapter.setAll(s, p.data));
addFulfilled(createOneThunk, (s, p) => adapter.addOne(s, p));
addFulfilled(updateOneThunk, (s, p) => adapter.upsertOne(s, p));
addFulfilled(deleteOneThunk, (s, p) => adapter.removeOne(s, p));
// Pending & Rejected matchers
type AnyThunk =
| typeof fetchAllThunk
| typeof fetchByParamThunk
| typeof createOneThunk
| typeof updateOneThunk
| typeof deleteOneThunk;
const allThunks: Exclude<AnyThunk, undefined>[] = [
fetchAllThunk,
fetchByParamThunk,
createOneThunk,
updateOneThunk,
deleteOneThunk,
].filter((t): t is Exclude<AnyThunk, undefined> => t !== undefined);
allThunks.forEach((thunk) => {
builder
.addMatcher(thunk.pending.match, handlePending)
.addMatcher(thunk.rejected.match, handleRejected);
});
},
});
// ──────────────────────────────
// Selectors
// ──────────────────────────────
function makeSelectors<RootState>(selectSlice: (state: RootState) => SliceState) {
const base = adapter.getSelectors(selectSlice);
const selectByName = createSelector(
[base.selectAll, (_: RootState, query: string) => query.trim().toLowerCase()],
(entities, q) =>
q
? entities.filter((i) => (i.name ?? '').toLowerCase().includes(q))
: entities,
);
const selectIsLoading = createSelector(
[selectSlice],
(s) => s.loading === ENTITY_LOADING_STATUSES.PENDING,
);
const selectError = createSelector([selectSlice], (s) => s.error);
return { ...base, selectByName, selectIsLoading, selectError };
}
// ──────────────────────────────
// Public API
// ──────────────────────────────
return {
reducer: slice.reducer,
actions: slice.actions,
adapter,
thunks: {
fetchAllThunk,
fetchByParamThunk,
createOneThunk,
updateOneThunk,
deleteOneThunk,
},
makeSelectors,
} as const;
}
|