2016-11-14 10:58:25 +05:30
|
|
|
import { ADD, REMOVE, ACTIVATE, RESET, UPDATE_TOKEN } from './actions';
|
2016-10-30 17:42:49 +05:30
|
|
|
|
|
|
|
/**
|
|
|
|
* @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: []
|
|
|
|
},
|
2016-10-30 17:42:49 +05:30
|
|
|
{type, payload = {}}
|
|
|
|
) {
|
|
|
|
switch (type) {
|
|
|
|
case ADD:
|
2016-11-19 21:20:30 +05:30
|
|
|
if (!payload || !payload.id || !payload.token) {
|
2016-10-30 17:42:49 +05:30
|
|
|
throw new Error('Invalid or empty payload passed for accounts.add');
|
|
|
|
}
|
|
|
|
|
2016-11-13 02:01:44 +05:30
|
|
|
state.available = state.available
|
|
|
|
.filter((account) => account.id !== payload.id)
|
|
|
|
.concat(payload);
|
2016-10-30 17:42:49 +05:30
|
|
|
|
2016-11-13 17:46:21 +05:30
|
|
|
state.available.sort((account1, account2) => {
|
|
|
|
if (account1.username === account2.username) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
return account1.username > account2.username ? 1 : -1;
|
|
|
|
});
|
|
|
|
|
2016-10-30 17:42:49 +05:30
|
|
|
return state;
|
|
|
|
|
|
|
|
case ACTIVATE:
|
2016-11-19 21:20:30 +05:30
|
|
|
if (!payload || !payload.id || !payload.token) {
|
2016-10-30 17:42:49 +05:30
|
|
|
throw new Error('Invalid or empty payload passed for accounts.add');
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
...state,
|
|
|
|
active: payload
|
|
|
|
};
|
|
|
|
|
2016-11-14 10:58:25 +05:30
|
|
|
case RESET:
|
|
|
|
return accounts(undefined, {});
|
|
|
|
|
2016-10-30 17:42:49 +05:30
|
|
|
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');
|
|
|
|
}
|
|
|
|
|
2016-10-30 17:42:49 +05:30
|
|
|
return {
|
2016-11-05 15:41:41 +05:30
|
|
|
...state,
|
|
|
|
active: {
|
|
|
|
...state.active,
|
|
|
|
token: payload
|
|
|
|
}
|
2016-10-30 17:42:49 +05:30
|
|
|
};
|
2016-11-05 15:41:41 +05:30
|
|
|
|
|
|
|
default:
|
|
|
|
return state;
|
2016-10-30 17:42:49 +05:30
|
|
|
}
|
|
|
|
}
|