All files / src/contexts/userContext userContext.tsx

50.55% Statements 46/91
17.65% Branches 6/34
25% Functions 8/32
51.14% Lines 45/88

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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223                                  5x               5x                                     5x   5x     2x 2x     5x 12x       2x         2x 2x               2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x                   2x 2x       2x                   2x           2x                 2x             2x       2x       2x           2x           2x           2x       2x           2x           2x 2x     2x 2x     2x 2x                                                                         2x  
import React, { useState, useContext, createContext, useEffect, useMemo, useCallback } from 'react';
import { useQuery, useMutation } from '@apollo/client';
import { UserContextType, CustomerAddress, CustomerUserData } from './types';
import {
  CREATE_TOKEN,
  GET_USER,
  CREATE_USER,
  CHANGE_PASSWORD,
  RESET_PASSWORD,
  REQUEST_RESET_PASSWORD,
  CREATE_ADDRESS,
  UPDATE_ADDRESS,
  DELETE_ADDRESS,
  UPDATE_USER_DATA,
  UPDATE_USER_EMAIL
} from './queries';
 
const defaultError = {
  signinError: '',
  signupError: '',
  signoutError: '',
  resetPasswordError: '',
  sendResetPasswordEmailError: ''
}
 
export const UserContext = createContext<UserContextType>({
  isAuth: false,
  user: null,
  signin: (email, password) => { },
  signout: () => { },
  signup: () => { },
  sendResetPasswordEmail: (email) => true,
  changePassword: (password, newPassword) => {},
  resetPassword: (email, token, password) => true,
  createAddress: (address) => true,
  updateAddress: (addressId, addressData) => true,
  deleteAddress: (addressId) => true,
  loading: false,
  error: defaultError,
  resetError: () => { },
  updateUserData: (userData) => {},
  updateUserEmail: (email, password) => {}
});
 
const { Provider } = UserContext;
 
export const UserProvider: React.FC<{ children: React.ReactNode }> = ({
  children
}) => {
  const auth: UserContextType = useProvideUser();
  return <Provider value={auth}> {children} </Provider>;
};
 
export const useUserContext = () => {
  return useContext(UserContext);
};
 
function useProvideUser() {
  const [userToken, setUserToken] = useState<string | null>(
    typeof window !== 'undefined' ? localStorage.getItem('ks-token') : null
  );
 
  // ToDo: loading statuses
  const [error, setError] = useState(defaultError);
  const [loading, setLoading] = useState(false);
 
  const {
    client,
    data: userData,
    loading: getUserLoading,
    error: getUserError,
    refetch: refetchUserData
  } = useQuery(GET_USER, { skip: !userToken });
 
  const [createToken] = useMutation(CREATE_TOKEN, { errorPolicy: 'all' });
  const [createUser] = useMutation(CREATE_USER, { errorPolicy: 'all' });
  const [requestResetPassword] = useMutation(REQUEST_RESET_PASSWORD, { errorPolicy: 'all' });
  const [resetUserPassword] = useMutation(RESET_PASSWORD, { errorPolicy: 'all' });
  const [createUserAddress] = useMutation(CREATE_ADDRESS, { errorPolicy: 'all' });
  const [updateUserAddress] = useMutation(UPDATE_ADDRESS, { errorPolicy: 'all' });
  const [deleteUserAddress] = useMutation(DELETE_ADDRESS, { errorPolicy: 'all' });
  const [changePasswordMutation] = useMutation(CHANGE_PASSWORD, { errorPolicy: 'all' });
  const [updateUserDataMutation] = useMutation(UPDATE_USER_DATA, { errorPolicy: 'all' });
  const [updateUserEmailMutation] = useMutation(UPDATE_USER_EMAIL, { errorPolicy: 'all' });
 
  useEffect(() => {
    Iif (userToken && !getUserLoading && getUserError
      && getUserError.graphQLErrors.length > 0
      && getUserError.graphQLErrors[0].extensions
      && getUserError.graphQLErrors[0].extensions.category === 'graphql-authorization') {
      // the customer token has expired
      // magento hasn“t refresh token endpoint
      signout();
    }
  }, [getUserError]);
 
  useEffect(() => {
    Eif (!userToken) return;
    refetchUserData();
  }, [userToken]);
 
  const signin = async (email: string, password: string) => {
    const response = await createToken({ variables: { email, password } });
    const err = response.errors ? response.errors[0].message : '';
    setError({ ...error, signinError: err });
    if (response.data && response.data.generateCustomerToken) {
      setUserToken(response.data.generateCustomerToken.token);
      if (typeof window !== 'undefined') localStorage.setItem('ks-token', response.data.generateCustomerToken.token);
    }
  };
 
  const signout = useCallback(() => {
    setUserToken(null);
    if (typeof window !== 'undefined') localStorage.removeItem('ks-token');
    client.resetStore();
  }, []);
 
  const signup = async (firstname: string, lastname: string, email: string, password: string) => {
    const response = await createUser({ variables: { firstname, lastname, email, password } });
    const err = response.errors ? response.errors[0].message : '';
    setError({ ...error, signupError: err });
    if (response.data.createCustomerV2 && response.data.createCustomerV2.customer) {
      signin(email, password);
    }
  }
 
  const sendResetPasswordEmail = async (email: string) => {
    const response = await requestResetPassword({ variables: { email } });
    const err = response.errors ? response.errors[0].message : '';
    setError({ ...error, sendResetPasswordEmailError: err });
    return response.data.requestPasswordResetEmail;
  };
 
  const changePassword = async (password: string, newPassword: string) => {
    return await changePasswordMutation({ variables: { password, newPassword } });
  };
 
  const resetPassword = useCallback(async (email: string, resetPasswordToken: string, newPassword: string) => {
    return await resetUserPassword({ variables: { email, resetPasswordToken, newPassword } });
  }, []);
 
  const createAddress = useCallback(async (address: CustomerAddress) => {
    const response = await createUserAddress({ variables: { address } })
    await refetchUserData();
    return response;
  }, []);
 
  const updateAddress = useCallback(async (addressId: number, address: CustomerAddress) => {
    const response = await updateUserAddress({ variables: { addressId, address } })
    await refetchUserData();
    return response;
  }, []);
 
  const deleteAddress = useCallback(async (addressId: number) => {
    const response = await deleteUserAddress({ variables: { addressId } })
    await refetchUserData();
    return response;
  }, []);
 
  const resetError = () => {
    setError(defaultError);
  }
 
  const updateUserData = useCallback(async (userData: CustomerUserData) => {
    const response = await updateUserDataMutation({ variables: { userData } });
    await refetchUserData();
    return response;
  }, []);
 
  const updateUserEmail = useCallback(async (email: string, password: string) => {
    const response = await updateUserEmailMutation({ variables: { email, password } });
    await refetchUserData();
    return response;
  }, []);
 
  const isAuth = useMemo(() => {
    return !!userToken;
  }, [userToken]);
 
  const user = useMemo(() => {
    return userData && !!isAuth ? userData.customer : userData
  }, [userData, isAuth]);
 
  const userState = useMemo(() => {
    return {
      isAuth,
      user,
      loading,
      error,
      resetError,
      signin,
      signout,
      signup,
      resetPassword,
      sendResetPasswordEmail,
      createAddress,
      updateAddress,
      deleteAddress,
      changePassword,
      updateUserData,
      updateUserEmail
    }
  }, [
    userToken,
    userData,
    loading,
    error,
    resetError,
    signin,
    signout,
    signup,
    resetPassword,
    sendResetPasswordEmail,
    createAddress,
    updateAddress,
    deleteAddress,
    changePassword,
    updateUserData,
    updateUserEmail
  ]);
 
  return userState;
}