I am wondering how I would refactor the following. Basically, after I get the user information from google, it is validated since a specific domain might be allowed. If it passes that one, we validate the token against a back end api.

Sonar is complaining on the use of return displayAlert('LoginFailed') three times. Given the methods have unique use, I am wondering what could be done to improve it?

import React, {useContext} from 'react'; import {View, Alert} from 'react-native'; import {LocalizationContext} from 'library/localization'; import ServiceAuth from 'services/ServiceAuth'; import {saveLoggedInDetails} from 'library/userInformation'; const MyComponent = (props) => { const {translations} = useContext(LocalizationContext); const displayAlert = (msg) =>{ //translations happen here Alert.alert("Failed", msg) return false; } const validateToken = async (userGoogleInfo) => { const {idToken} = userGoogleInfo; let serviceAuth = ServiceAuth.getInstance(); try { return await serviceAuth.validateT(idToken); } catch (error) { //show alert here return displayAlert('LoginFailed') } }; const authorize = async (userGoogleInfo) => { const allowedDomains = []; let reply = {ok: false}; //check if domain is allowed etc and set to true. if (!reply['ok']) { return displayAlert('InvalidDomain'); } try { const userInfo = await validateToken(userGoogleInfo); if (userInfo) { console.log("okay") } else { return displayAlert('LoginFailed') } } catch (error) { return displayAlert('LoginFailed') } }; return ( <> <View> <Text>Hello</Text> </View> </> ); }; export default MyComponent; 

1 Answer

The message is a little bit confusing but sonar is complaining only about the LoginFailed string used three times as parameter.

Create a constant as, for example:

const LOGIN_FAILED = 'LoginFailed'; 

And then use it in all the three calls to displayAlert:

return displayAlert(LOGIN_FAILED); 
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy