Advertisement
Guest User

Vuex Example

a guest
Oct 1st, 2018
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Utils
  3.  */
  4.  
  5. import setToInitialState from '@/store/utils/set-to-initial-state';
  6. import createGetter from '@/store/utils/create-getter';
  7. import {
  8.   createStatuses,
  9.   createMutations,
  10.   commitStatus,
  11. } from '@/store/utils/create-internals';
  12. import createTypesObject from '@/store/utils/create-types-object';
  13.  
  14. /**
  15.  * Data
  16.  */
  17.  
  18. import Roles from '@/data/enum/roles';
  19. import API_CONFIG from '@/data/api-config';
  20. import Statuses from '@/data/enum/generic-statuses';
  21.  
  22.  
  23. /**
  24.  * Misc
  25.  */
  26.  
  27. import Vue from 'vue';
  28. import toUrlSearchParams from '@/utils/helpers/to-url-search-params';
  29. import { get } from 'lodash';
  30.  
  31. const AsyncActionTypes = {
  32.   loadUsers: 'loadUsers',
  33.   loadUser: 'loadUser',
  34.   loadUserAddresses: 'loadUserAddresses',
  35.   createUser: 'createUser',
  36.   updateUser: 'updateUser',
  37.   toggleUser: 'toggleUser',
  38.   loginAs: 'loginAs',
  39.   passwordReset: 'passwordReset',
  40.   loadAssigneeOptions: 'loadAssigneeOptions',
  41. };
  42.  
  43. const SyncActionTypes = {
  44.   clearUser: 'clearUser',
  45.   resetUsersState: 'resetUsersState',
  46. };
  47.  
  48. const initialState = () => ({
  49.   ...createStatuses(AsyncActionTypes),
  50.  
  51.   users: null,
  52.   user: null,
  53.   userAddresses: null,
  54.   sudosuToken: '',
  55.   assigneeOptions: [],
  56. });
  57.  
  58. export const UsersStateProps = createTypesObject(initialState(), 'UserStateProps');
  59.  
  60. const getters = {
  61.   ...createGetter('user', 'user.data'),
  62.   ...createGetter('users', 'users.data'),
  63.   ...createGetter('userAddresses', 'userAddresses.data'),
  64.   ...createGetter('totalNumberOfUsers', 'users.meta.total'),
  65.   ...createGetter('totalNumberOfPages', 'users.meta.last_page'),
  66.   ...createGetter('usersPerPage', 'users.meta.per_page'),
  67.   ...createGetter('sudosuToken'),
  68.   ...createGetter('assigneeOptions'),
  69. };
  70.  
  71. export const UsersGetterTypes = createTypesObject(getters, 'UsersGetterTypes');
  72.  
  73. const mutations = {
  74.   ...createMutations(AsyncActionTypes),
  75.  
  76.   SAVE_USERS(state, responseData) {
  77.     state.users = responseData;
  78.   },
  79.   SAVE_USER(state, responseData) {
  80.     state.user = responseData;
  81.   },
  82.   SAVE_USER_ADDRESSES(state, responseData) {
  83.     state.userAddresses = responseData;
  84.   },
  85.   SAVE_SUDOSU_TOKEN(state, token) {
  86.     state.sudosuToken = token;
  87.   },
  88.   SAVE_ASSIGNEE_OPTIONS(state, responseData) {
  89.     state.assigneeOptions = responseData;
  90.   },
  91.   CLEAR_USER(state) {
  92.     state.user = initialState().user;
  93.   },
  94.   RESET_STATE(state) {
  95.     setToInitialState(state, initialState());
  96.   },
  97. };
  98.  
  99. export const UsersMutationTypes = createTypesObject(mutations, 'UsersMutationTypes');
  100.  
  101. const actions = {
  102.   /**
  103.    * @desc Load users.
  104.    *
  105.    * @param {Object} context
  106.    * @param {{ [roles]: string, [search]: string, [sort]: string, [page]: number|string }} query
  107.    * @returns {Promise} paginated collection.
  108.    */
  109.   async [AsyncActionTypes.loadUsers]({ commit }, query) {
  110.     const actionType = AsyncActionTypes.loadUsers;
  111.  
  112.     try {
  113.       commitStatus(commit, actionType, Statuses.PENDING);
  114.  
  115.       const urlSearchParams = toUrlSearchParams(query);
  116.  
  117.       const { method, path } = API_CONFIG.XXX.ENDPOINTS.USER.LIST_USERS;
  118.  
  119.       const responseData = await Vue.http[method](`${path}?${urlSearchParams}`);
  120.  
  121.       commit(UsersMutationTypes.SAVE_USERS, responseData);
  122.  
  123.       commitStatus(commit, actionType, Statuses.FULFILLED);
  124.  
  125.       return responseData;
  126.     } catch (error) {
  127.       if (process.env.VUE_APP_CONSOLE_MESSAGES === 'on') {
  128.         console.warn('[UsersModule] An error occurred while retrieving list of users.', error || '(no data)');
  129.       }
  130.  
  131.       commitStatus(commit, actionType, Statuses.REJECTED);
  132.  
  133.       throw error;
  134.     }
  135.   },
  136.  
  137.   /**
  138.    * @desc Get user by id.
  139.    *
  140.    * @param {Object} context
  141.    * @param {number|string} userId
  142.    * @returns {Promise}
  143.    */
  144.   async [AsyncActionTypes.loadUser]({ commit }, userId) {
  145.     const actionType = AsyncActionTypes.loadUser;
  146.  
  147.     try {
  148.       commitStatus(commit, actionType, Statuses.PENDING);
  149.  
  150.       const { method, path } = API_CONFIG.XXX.ENDPOINTS.USER.GET_USER;
  151.  
  152.       const responseData = await Vue.http[method](path.replace('{id}', userId));
  153.  
  154.       commit(UsersMutationTypes.SAVE_USER, responseData);
  155.  
  156.       commitStatus(commit, actionType, Statuses.FULFILLED);
  157.  
  158.       return responseData;
  159.     } catch (error) {
  160.       if (process.env.VUE_APP_CONSOLE_MESSAGES === 'on') {
  161.         console.warn('[UsersModule] An error occurred while retrieving a user data.', error || '(no data)');
  162.       }
  163.  
  164.       commitStatus(commit, actionType, Statuses.REJECTED);
  165.  
  166.       throw error;
  167.     }
  168.   },
  169.  
  170.   /**
  171.    * @desc List user addresses by id.
  172.    *
  173.    * @param {Object} context
  174.    * @param {number|string} userId
  175.    * @returns {Promise}
  176.    */
  177.   async [AsyncActionTypes.loadUserAddresses]({ commit }, userId) {
  178.     const actionType = AsyncActionTypes.loadUserAddresses;
  179.  
  180.     try {
  181.       commitStatus(commit, actionType, Statuses.PENDING);
  182.  
  183.       const { method, path } = API_CONFIG.XXX.ENDPOINTS.USER.LIST_USER_ADDRESSES;
  184.  
  185.       const responseData = await Vue.http[method](path.replace('{id}', userId));
  186.  
  187.       commit(UsersMutationTypes.SAVE_USER_ADDRESSES, responseData);
  188.  
  189.       commitStatus(commit, actionType, Statuses.FULFILLED);
  190.  
  191.       return responseData;
  192.     } catch (error) {
  193.       if (process.env.VUE_APP_CONSOLE_MESSAGES === 'on') {
  194.         console.warn('[UsersModule] An error occurred while loading list of user addresses.', error || '(no data)');
  195.       }
  196.  
  197.       commitStatus(commit, actionType, Statuses.REJECTED);
  198.  
  199.       throw error;
  200.     }
  201.   },
  202.  
  203.   /**
  204.    * @desc Create user.
  205.    *
  206.    * @param {Object} context
  207.    * @param {{ role: string, email: string,
  208.    * first_name: string, last_name: string, [phone]: string }} user
  209.    * @returns {Promise}
  210.    */
  211.   async [AsyncActionTypes.createUser]({ commit }, user) {
  212.     const actionType = AsyncActionTypes.createUser;
  213.  
  214.     try {
  215.       commitStatus(commit, actionType, Statuses.PENDING);
  216.  
  217.       const { method, path } = API_CONFIG.XXX.ENDPOINTS.USER.CREATE_USER;
  218.  
  219.       const responseData = await Vue.http[method](path, user);
  220.  
  221.       commitStatus(commit, actionType, Statuses.FULFILLED);
  222.  
  223.       return responseData;
  224.     } catch (error) {
  225.       if (process.env.VUE_APP_CONSOLE_MESSAGES === 'on') {
  226.         console.warn('[UsersModule] An error occurred while creating a user.', error || '(no data)');
  227.       }
  228.  
  229.       commitStatus(commit, actionType, Statuses.REJECTED);
  230.  
  231.       throw error;
  232.     }
  233.   },
  234.  
  235.   /**
  236.    * @desc Update user by id.
  237.    * If User is granted 'Admin' – use Update User, otherwise – use Update User Details.
  238.    *
  239.    * @param {Object} context
  240.    * @param {{ id: number|string, data: { role: string,
  241.    * first_name: string, last_name: string, [phone]: string }
  242.    * | {first_name: string, last_name: string, [phone]: string} }} user
  243.    * @returns {Promise}
  244.    */
  245.   async [AsyncActionTypes.updateUser]({ commit }, user) {
  246.     const actionType = AsyncActionTypes.updateUser;
  247.  
  248.     try {
  249.       commitStatus(commit, actionType, Statuses.PENDING);
  250.  
  251.       let responseData;
  252.  
  253.       const { id, data } = user;
  254.  
  255.       const isGrantedAdmin = Vue.auth.checkRole(Roles.ADMIN);
  256.  
  257.       if (isGrantedAdmin) {
  258.         const { method, path } = API_CONFIG.XXX.ENDPOINTS.USER.UPDATE_USER;
  259.  
  260.         responseData = await Vue.http[method](path.replace('{id}', id), data);
  261.       } else {
  262.         const { method, path } = API_CONFIG.XXX.ENDPOINTS.USER.UPDATE_USER_DETAILS;
  263.  
  264.         responseData = await Vue.http[method](path.replace('{id}', id), data);
  265.       }
  266.  
  267.       commitStatus(commit, actionType, Statuses.FULFILLED);
  268.  
  269.       return responseData;
  270.     } catch (error) {
  271.       if (process.env.VUE_APP_CONSOLE_MESSAGES === 'on') {
  272.         console.warn('[UserModule] An error occurred while updating user data.', error || '(no data)');
  273.       }
  274.  
  275.       commitStatus(commit, actionType, Statuses.REJECTED);
  276.  
  277.       throw error;
  278.     }
  279.   },
  280.  
  281.   /**
  282.    * @desc Toggle user.
  283.    *
  284.    * @param {Object} context
  285.    * @param {{ isDisabledNow: boolean, user_id: number|string }} user
  286.    * @returns {Promise}
  287.    */
  288.   async [AsyncActionTypes.toggleUser]({ commit }, user) {
  289.     const actionType = AsyncActionTypes.toggleUser;
  290.  
  291.     try {
  292.       commitStatus(commit, actionType, Statuses.PENDING);
  293.  
  294.       let responseData;
  295.  
  296.       if (user.isDisabledNow) {
  297.         const { method, path } = API_CONFIG.XXX.ENDPOINTS.USER.DELETE_DISABLED_USER;
  298.  
  299.         responseData = await Vue.http[method](path.replace('{id}', user.id));
  300.       } else {
  301.         const { method, path } = API_CONFIG.XXX.ENDPOINTS.USER.CREATE_DISABLED_USER;
  302.  
  303.         responseData = await Vue.http[method](path, { user_id: user.id });
  304.       }
  305.  
  306.       commitStatus(commit, actionType, Statuses.FULFILLED);
  307.  
  308.       return responseData;
  309.     } catch (error) {
  310.       if (process.env.VUE_APP_CONSOLE_MESSAGES === 'on') {
  311.         console.warn('[UsersModule] An error occurred while toggling user.', error || '(no data)');
  312.       }
  313.  
  314.       commitStatus(commit, actionType, Statuses.REJECTED);
  315.  
  316.       throw error;
  317.     }
  318.   },
  319.  
  320.   /**
  321.    * @desc Login As.
  322.    *
  323.    * @param {Object} context
  324.    * @param {number|string} id
  325.    * @returns {Promise}
  326.    */
  327.   async [AsyncActionTypes.loginAs]({ commit }, id) {
  328.     const actionType = AsyncActionTypes.loginAs;
  329.  
  330.     try {
  331.       commitStatus(commit, actionType, Statuses.PENDING);
  332.  
  333.       const { method, path } = API_CONFIG.XXX.ENDPOINTS.USER.CREATE_SUDOSU_TOKEN;
  334.  
  335.       const responseData = await Vue.http[method](path, { user_id: id });
  336.  
  337.       commit(UsersMutationTypes.SAVE_SUDOSU_TOKEN, get(responseData, 'data.token'));
  338.  
  339.       commitStatus(commit, actionType, Statuses.FULFILLED);
  340.  
  341.       return responseData;
  342.     } catch (error) {
  343.       if (process.env.VUE_APP_CONSOLE_MESSAGES === 'on') {
  344.         console.warn('[UsersModule] An error occurred while logging as.', error || '(no data)');
  345.       }
  346.  
  347.       commitStatus(commit, actionType, Statuses.REJECTED);
  348.  
  349.       throw error;
  350.     }
  351.   },
  352.  
  353.   /**
  354.    * @desc Password reset.
  355.    *
  356.    * @param {Object} context
  357.    * @param {{ token: string, email: string, password: string }} data
  358.    * @returns {Promise}
  359.    */
  360.   async [AsyncActionTypes.passwordReset]({ commit }, data) {
  361.     const actionType = AsyncActionTypes.passwordReset;
  362.  
  363.     try {
  364.       commitStatus(commit, actionType, Statuses.PENDING);
  365.  
  366.       const { method, path } = API_CONFIG.XXX.ENDPOINTS.ACCOUNT.CREATE_PASSWORD_RESET;
  367.  
  368.       const responseData = await Vue.http[method](path, data);
  369.  
  370.       commitStatus(commit, actionType, Statuses.FULFILLED);
  371.  
  372.       return responseData;
  373.     } catch (error) {
  374.       if (process.env.VUE_APP_CONSOLE_MESSAGES === 'on') {
  375.         console.warn('[UsersModule] An error occurred while resetting password.', error || '(no data)');
  376.       }
  377.  
  378.       commitStatus(commit, actionType, Statuses.REJECTED);
  379.  
  380.       throw error;
  381.     }
  382.   },
  383.  
  384.   /**
  385.    * @desc Load list of assignable users.
  386.    *
  387.    * @param {Object} context
  388.    * @returns {Promise}
  389.    */
  390.   async [AsyncActionTypes.loadAssigneeOptions]({ commit }) {
  391.     const actionType = AsyncActionTypes.loadAssigneeOptions;
  392.  
  393.     try {
  394.       commitStatus(commit, actionType, Statuses.PENDING);
  395.  
  396.       const { method, path } = API_CONFIG.XXX.ENDPOINTS.USER.LIST_ASSIGNEE_OPTIONS;
  397.  
  398.       const responseData = await Vue.http[method](path);
  399.  
  400.       commit(UsersMutationTypes.SAVE_ASSIGNEE_OPTIONS, responseData.data);
  401.  
  402.       commitStatus(commit, actionType, Statuses.FULFILLED);
  403.  
  404.       return responseData;
  405.     } catch (error) {
  406.       if (process.env.VUE_APP_CONSOLE_MESSAGES === 'on') {
  407.         console.warn('[UsersModule] An error occurred while retrieving list of assignable users.', error || '(no data)');
  408.       }
  409.  
  410.       commitStatus(commit, actionType, Statuses.REJECTED);
  411.  
  412.       throw error;
  413.     }
  414.   },
  415.  
  416.   /**
  417.    * @desc Remove user's info from the store.
  418.    *
  419.    * @param {Object} context
  420.    */
  421.   [SyncActionTypes.clearUser]({ commit }) {
  422.     commit(UsersMutationTypes.CLEAR_USER);
  423.   },
  424.  
  425.   /**
  426.    * Reset full module's state to it's initial state.
  427.    *
  428.    * @param {Object} context
  429.    */
  430.   [SyncActionTypes.resetUsersState]({ commit }) {
  431.     commit(UsersMutationTypes.RESET_STATE);
  432.   },
  433. };
  434.  
  435. export const UsersActionTypes = createTypesObject(actions, 'UsersActionTypes');
  436.  
  437. export default {
  438.   namespaced: true,
  439.  
  440.   state: initialState(),
  441.  
  442.   getters,
  443.  
  444.   mutations,
  445.  
  446.   actions,
  447. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement