1
- import { CRUD_GET_MANY_SUCCESS , CRUD_GET_LIST_SUCCESS , CRUD_DELETE_SUCCESS } from '../../../actions/dataActions' ;
1
+ import { CRUD_GET_LIST_SUCCESS , CRUD_DELETE_SUCCESS } from '../../../actions/dataActions' ;
2
2
3
- const cacheDuration = 10 * 60 * 1000 ; // ten minutes
4
-
5
- /**
6
- * Add new records to the pool, and remove outdated ones.
7
- *
8
- * This is the equivalent of a stale-while-revalidate caching strategy:
9
- * The cached data is displayed before fetching, and stale data is removed
10
- * only once fresh data is fetched.
11
- */
12
- const addRecords = ( newRecords = [ ] , oldRecords ) => {
13
- const now = new Date ( ) ;
14
- const newRecordsFetchedAt = newRecords . reduce ( ( prev , record ) => {
15
- prev [ record ] = now ; // eslint-disable-line no-param-reassign
16
- return prev ;
17
- } , [ ] ) ;
18
- // remove outdated old records
19
- const latestValidDate = new Date ( ) ;
20
- latestValidDate . setTime ( latestValidDate . getTime ( ) - cacheDuration ) ;
21
- const oldValidRecordIds = oldRecords . fetchedAt
22
- ? Object . keys ( oldRecords . fetchedAt )
23
- . filter ( id => oldRecords . fetchedAt [ id ] > latestValidDate )
24
- : [ ] ;
25
- const oldValidRecords = oldValidRecordIds . reduce ( ( prev , id ) => {
26
- prev [ id ] = oldRecords [ id ] ; // eslint-disable-line no-param-reassign
27
- return prev ;
28
- } , [ ] ) ;
29
- const oldValidRecordsFetchedAt = oldValidRecordIds . reduce ( ( prev , id ) => {
30
- prev [ id ] = oldRecords . fetchedAt [ id ] ; // eslint-disable-line no-param-reassign
31
- return prev ;
32
- } , [ ] ) ;
33
- // combine old records and new records
34
- const records = [
35
- ...oldValidRecords ,
36
- ...newRecords ,
37
- ] ;
38
- Object . defineProperty ( records , 'fetchedAt' , { value : {
39
- ...oldValidRecordsFetchedAt ,
40
- ...newRecordsFetchedAt ,
41
- } } ) ; // non enumerable by default
42
- return records ;
43
- } ;
44
-
45
- const initialState = [ ] ;
46
- Object . defineProperty ( initialState , 'fetchedAt' , { value : { } } ) ; // non enumerable by default
47
-
48
- export default resource => ( previousState = initialState , { type, payload, requestPayload, meta } ) => {
3
+ export default resource => ( previousState = [ ] , { type, payload, requestPayload, meta } ) => {
49
4
if ( ! meta || meta . resource !== resource ) {
50
5
return previousState ;
51
6
}
52
7
switch ( type ) {
53
- case CRUD_GET_MANY_SUCCESS :
54
- return addRecords ( payload . data . map ( record => record . id ) , previousState ) ;
55
8
case CRUD_GET_LIST_SUCCESS :
56
9
return payload . data . map ( record => record . id ) ;
57
10
case CRUD_DELETE_SUCCESS : {
@@ -66,4 +19,4 @@ export default resource => (previousState = initialState, { type, payload, reque
66
19
}
67
20
} ;
68
21
69
- export const getIds = state => state ;
22
+ export const getIds = ( state ) => state ;
0 commit comments