accounts-frontend/src/components/accounts/reducer.js

72 lines
1.8 KiB
JavaScript
Raw Normal View History

2016-11-05 15:41:41 +05:30
import { ADD, REMOVE, ACTIVATE, UPDATE_TOKEN } from './actions';
/**
* @typedef {AccountsState}
* @property {Account} active
* @property {Account[]} available
*/
/**
* @param {AccountsState} state
* @param {string} options.type
* @param {object} options.payload
*
* @return {AccountsState}
*/
export default function accounts(
2016-11-05 15:41:41 +05:30
state = {
active: null,
available: []
},
{type, payload = {}}
) {
switch (type) {
case ADD:
if (!payload || !payload.id || !payload.token || !payload.refreshToken) {
throw new Error('Invalid or empty payload passed for accounts.add');
}
state.available = state.available
.filter((account) => account.id !== payload.id)
.concat(payload);
return state;
case ACTIVATE:
if (!payload || !payload.id || !payload.token || !payload.refreshToken) {
throw new Error('Invalid or empty payload passed for accounts.add');
}
return {
...state,
active: payload
};
case REMOVE:
if (!payload || !payload.id) {
throw new Error('Invalid or empty payload passed for accounts.remove');
}
return {
...state,
available: state.available.filter((account) => account.id !== payload.id)
};
2016-11-05 15:41:41 +05:30
case UPDATE_TOKEN:
if (typeof payload !== 'string') {
throw new Error('payload must be a jwt token');
}
return {
2016-11-05 15:41:41 +05:30
...state,
active: {
...state.active,
token: payload
}
};
2016-11-05 15:41:41 +05:30
default:
return state;
}
}