2016-08-10 21:36:11 +02:00
|
|
|
/**
|
|
|
|
* This implements a wrapper to create reducers for paginated content.
|
|
|
|
*/
|
|
|
|
|
|
|
|
// NPM imports
|
2016-08-01 00:26:52 +02:00
|
|
|
import Immutable from "immutable";
|
2016-07-07 23:23:18 +02:00
|
|
|
|
2016-08-10 21:36:11 +02:00
|
|
|
// Local imports
|
2016-08-01 00:26:52 +02:00
|
|
|
import { createReducer } from "../utils";
|
2016-07-07 23:23:18 +02:00
|
|
|
|
2016-08-10 21:36:11 +02:00
|
|
|
// Models
|
|
|
|
import { stateRecord } from "../models/paginated";
|
|
|
|
|
|
|
|
// Actions
|
2016-08-10 23:50:23 +02:00
|
|
|
import { CLEAR_PAGINATED_RESULTS, INVALIDATE_STORE } from "../actions";
|
2016-08-10 21:36:11 +02:00
|
|
|
|
|
|
|
|
|
|
|
/** Initial state of the reducer */
|
2016-08-01 00:26:52 +02:00
|
|
|
const initialState = new stateRecord();
|
2016-07-07 23:23:18 +02:00
|
|
|
|
2016-08-10 21:36:11 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Creates a reducer managing pagination, given the action types to handle.
|
|
|
|
*/
|
|
|
|
export default function paginated(types) {
|
|
|
|
// Check parameters
|
2016-07-07 23:23:18 +02:00
|
|
|
if (!Array.isArray(types) || types.length !== 3) {
|
|
|
|
throw new Error("Expected types to be an array of three elements.");
|
|
|
|
}
|
|
|
|
if (!types.every(t => typeof t === "string")) {
|
|
|
|
throw new Error("Expected types to be strings.");
|
|
|
|
}
|
|
|
|
|
|
|
|
const [ requestType, successType, failureType ] = types;
|
|
|
|
|
2016-08-10 21:36:11 +02:00
|
|
|
// Create reducer
|
2016-07-07 23:23:18 +02:00
|
|
|
return createReducer(initialState, {
|
|
|
|
[requestType]: (state) => {
|
2016-08-10 21:36:11 +02:00
|
|
|
return state;
|
2016-07-07 23:23:18 +02:00
|
|
|
},
|
|
|
|
[successType]: (state, payload) => {
|
2016-08-01 00:26:52 +02:00
|
|
|
return (
|
|
|
|
state
|
2016-08-10 21:36:11 +02:00
|
|
|
.set("type", payload.type)
|
2016-08-05 00:00:25 +02:00
|
|
|
.set("result", Immutable.fromJS(payload.result))
|
2016-08-01 00:26:52 +02:00
|
|
|
.set("nPages", payload.nPages)
|
|
|
|
.set("currentPage", payload.currentPage)
|
|
|
|
);
|
2016-07-07 23:23:18 +02:00
|
|
|
},
|
2016-08-10 21:36:11 +02:00
|
|
|
[failureType]: (state) => {
|
|
|
|
return state;
|
|
|
|
},
|
2016-08-10 23:50:23 +02:00
|
|
|
[CLEAR_PAGINATED_RESULTS]: (state) => {
|
2016-08-10 21:36:11 +02:00
|
|
|
return state.set("result", new Immutable.List());
|
2016-08-03 15:52:47 +02:00
|
|
|
},
|
|
|
|
[INVALIDATE_STORE]: () => {
|
2016-08-10 21:36:11 +02:00
|
|
|
// Reset state on invalidation
|
2016-08-03 15:52:47 +02:00
|
|
|
return new stateRecord();
|
2016-08-10 23:50:23 +02:00
|
|
|
},
|
2016-07-07 23:23:18 +02:00
|
|
|
});
|
|
|
|
}
|