Repository navigation
Expand file tree
/
Copy pathcreateReducer.ts
More file actions
82 lines (72 loc) · 2.25 KB
/
Copy pathcreateReducer.ts
File metadata and controls
82 lines (72 loc) · 2.25 KB
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
import { expireReducer } from './expireReducer.js';
import { fetchReducer } from './fetchReducer.js';
import { invalidateReducer } from './invalidateReducer.js';
import { setReducer } from './setReducer.js';
import { setResponseReducer } from './setResponseReducer.js';
import {
SET,
INVALIDATE,
RESET,
FETCH,
GC,
OPTIMISTIC,
INVALIDATEALL,
EXPIREALL,
SET_RESPONSE,
} from '../../actionTypes.js';
import type Controller from '../../controller/Controller.js';
import type { ActionTypes, State } from '../../types.js';
export default function createReducer(controller: Controller): ReducerType {
return function reducer(
state: State<unknown> | undefined,
action: ActionTypes,
): State<unknown> {
if (!state) state = initialState;
switch (action.type) {
case GC:
// inline deletes are fine as these should have 0 refcounts
action.entities.forEach(({ key, pk }) => {
delete (state as any).entities[key]?.[pk];
delete (state as any).entitiesMeta[key]?.[pk];
});
action.endpoints.forEach(fetchKey => {
delete (state as any).endpoints[fetchKey];
delete (state as any).meta[fetchKey];
});
return state;
case FETCH:
return fetchReducer(state, action);
case OPTIMISTIC:
// eslint-disable-next-line no-fallthrough
case SET_RESPONSE:
return setResponseReducer(state, action, controller);
case SET:
return setReducer(state, action, controller);
case INVALIDATEALL:
case INVALIDATE:
return invalidateReducer(state, action);
case EXPIREALL:
return expireReducer(state, action);
case RESET:
return { ...initialState, lastReset: action.date };
default:
// A reducer must always return a valid state.
// Alternatively you can throw an error if an invalid action is dispatched.
return state;
}
} as any;
}
export const initialState: State<unknown> = {
entities: {},
endpoints: {},
indexes: {},
meta: {},
entitiesMeta: {},
optimistic: [],
lastReset: 0,
};
type ReducerType = (
state: State<unknown> | undefined,
action: ActionTypes,
) => State<unknown>;
type Writable<T> = { [P in keyof T]: NonNullable<Writable<T[P]>> };