E.W.O. Next / All files / src/engine/Users reducers.ts

100% Statements 26/26
100% Branches 7/7
100% Functions 5/5
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49          4x 4x 4x   4x   4x 4x   4x 4x       4x 12x     1x 1x 1x 1x     1x   1x     1x   1x     1x     1x 1x   7x      
/**
 * @module Engine.Users
 * Users reducers
 */
 
import { SaveDBCommand } from '@commands/index';
import { addLazyCommand } from '@engine/Commands/CommandsTools';
import { loadDatabaseList, saveDatabaseList } from '@engine/Commands/tasks';
import { User } from '@models';
import { List } from 'immutable';
import { AnyAction } from 'redux';
import { UsersActions } from './actions';
import { UsersTools } from './UsersTools';
 
const INITIAL_STATE: IUsersState = List();
const DATABASE = 'users';
 
export type IUsersState = List<User>;
 
export const usersReducers = (state: IUsersState = INITIAL_STATE, action: AnyAction) => {
  switch (action.type) {
 
    case UsersActions.REGISTER:
      const newUser: User = action.user;
      newUser.id = state.size;
      addLazyCommand(new SaveDBCommand());
      return state.push(newUser);
 
    case UsersActions.LOGIN:
      const userIndexLogin = state.findIndex(user => user.name === action.username);
 
      return state.update(userIndexLogin, (user: User) => ({ ...user, token: action.token }));
 
    case UsersActions.LOGOUT:
      const userIndexLogout = state.findIndex(user => user.token === action.token);
 
      return state.update(userIndexLogout, (user: User) => ({ ...user, token: undefined }));
 
    case UsersActions.LOAD_DATABASE:
      return loadDatabaseList(DATABASE, UsersTools.hydrater);
 
    case UsersActions.SAVE_DATABASE:
      saveDatabaseList(DATABASE, state, UsersTools.serializer);
      return state;
    default:
      return state;
  }
};