insomnia/app/reducers/requests.js

56 lines
1.5 KiB
JavaScript
Raw Normal View History

2016-03-20 04:00:40 +00:00
import * as types from "../constants/actionTypes";
2016-03-16 05:49:42 +00:00
2016-03-20 04:00:40 +00:00
const initialState = {
all: [],
2016-03-20 23:27:46 +00:00
active: null
2016-03-20 04:00:40 +00:00
};
2016-03-16 05:49:42 +00:00
2016-03-20 04:00:40 +00:00
function requestsReducer (state = [], action) {
switch (action.type) {
case types.REQUEST_ADD:
2016-03-20 23:39:46 +00:00
// Change name if there is a duplicate
const request = action.request;
for (let i = 0; ; i++) {
let name = i === 0 ? request.name : request.name + ` (${i})`;
if (!state.find(r => r.name === name)) {
request.name = name;
break;
}
}
return [...state, request];
2016-03-20 04:00:40 +00:00
case types.REQUEST_UPDATE:
2016-03-20 20:42:27 +00:00
return state.map(request => {
2016-03-20 23:20:00 +00:00
if (request.id === action.patch.id) {
return Object.assign({}, request, action.patch);
2016-03-20 20:42:27 +00:00
} else {
return request;
}});
2016-03-20 04:00:40 +00:00
default:
return state;
}
2016-03-16 05:49:42 +00:00
}
2016-03-20 04:00:40 +00:00
export default function (state = initialState, action) {
2016-03-20 23:27:46 +00:00
let all, active;
2016-03-20 04:00:40 +00:00
switch (action.type) {
case types.REQUEST_ADD:
all = requestsReducer(state.all, action);
2016-03-20 23:27:46 +00:00
active = state.active || action.request.id;
return Object.assign({}, state, {all, active});
2016-03-20 04:00:40 +00:00
case types.REQUEST_UPDATE:
all = requestsReducer(state.all, action);
2016-03-20 23:20:00 +00:00
return Object.assign({}, state, {all});
2016-03-20 04:47:43 +00:00
case types.REQUEST_ACTIVATE:
2016-03-20 23:20:00 +00:00
if (!state.all.find(r => r.id === action.id)) {
// Don't set if the request doesn't exist
return state;
} else {
2016-03-20 23:27:46 +00:00
return Object.assign({}, state, {active: action.id});
2016-03-20 23:20:00 +00:00
}
2016-03-20 04:00:40 +00:00
default:
return state
}
2016-03-16 05:49:42 +00:00
}