2016-08-01 00:26:52 +02:00
|
|
|
import Immutable from "immutable";
|
2016-07-07 23:23:18 +02:00
|
|
|
|
2016-08-01 00:26:52 +02:00
|
|
|
import { createReducer } from "../utils";
|
|
|
|
import { stateRecord } from "../models/paginate";
|
2016-08-03 15:52:47 +02:00
|
|
|
import { INVALIDATE_STORE } from "../actions";
|
2016-07-07 23:23:18 +02:00
|
|
|
|
2016-08-01 00:26:52 +02:00
|
|
|
const initialState = new stateRecord();
|
2016-07-07 23:23:18 +02:00
|
|
|
|
|
|
|
// Creates a reducer managing pagination, given the action types to handle,
|
|
|
|
// and a function telling how to extract the key from an action.
|
|
|
|
export default function paginate(types) {
|
|
|
|
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;
|
|
|
|
|
|
|
|
return createReducer(initialState, {
|
|
|
|
[requestType]: (state) => {
|
2016-08-01 00:26:52 +02:00
|
|
|
return (
|
|
|
|
state
|
|
|
|
.set("isFetching", true)
|
|
|
|
.set("error", null)
|
|
|
|
);
|
2016-07-07 23:23:18 +02:00
|
|
|
},
|
|
|
|
[successType]: (state, payload) => {
|
2016-08-01 00:26:52 +02:00
|
|
|
return (
|
|
|
|
state
|
|
|
|
.set("isFetching", false)
|
2016-08-05 00:00:25 +02:00
|
|
|
.set("result", Immutable.fromJS(payload.result))
|
|
|
|
.set("entities", Immutable.fromJS(payload.entities))
|
2016-08-01 00:26:52 +02:00
|
|
|
.set("error", null)
|
|
|
|
.set("nPages", payload.nPages)
|
|
|
|
.set("currentPage", payload.currentPage)
|
|
|
|
);
|
2016-07-07 23:23:18 +02:00
|
|
|
},
|
|
|
|
[failureType]: (state, payload) => {
|
2016-08-01 00:26:52 +02:00
|
|
|
return (
|
|
|
|
state
|
|
|
|
.set("isFetching", false)
|
|
|
|
.set("error", payload.error)
|
|
|
|
);
|
2016-08-03 15:52:47 +02:00
|
|
|
},
|
|
|
|
[INVALIDATE_STORE]: () => {
|
|
|
|
return new stateRecord();
|
2016-07-07 23:23:18 +02:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|