0

How do I return a value from a function running within a switch case statement?

I have been trying to return a value from within a function running inside a switch case statement. I have tried removing the break; statement and only using the return; statement but it ends up running until my default case.

My code is as presented below: ** bare in mind that every variable has been defined and imported initially as required **

function authorizeToken( req, tokenType ){
    //the token is stored in the request header's bearer attribute
    //the attribute is seperated from its value(token) by a space in the form 
    // Bearer token
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1]; //this code returns authHeader.split(' ')[1] if authHeader returns true
    if ( token == null ){ 
        return [ 'ERROR', 'Please provide a token' ];
    } else{
        //this takes the token and the secret used to encode , 
        //decodes the token and returns the userdata that was provided 
        //in the token. If it fails, it returns an error 
        switch( tokenType.toLowerCase() ){
            case 'access token':
                jwt.verify( token, process.env.JWT_ACCESS_TOKEN_SECRET, ( err, payload ) => {
                    if( err ) return [ 'ERROR', 'Token is invalid' ];
                    console.log( `AuthorizeToken - access token - here userName = ${ payload.userData }` );
                    return [ 'Success', payload.userData ]; 
                } );
            case 'refresh token':
                jwt.verify( token, process.env.JWT_REFRESH_TOKEN_SECRET, ( err, payload ) => {
                    if( err ) return [ 'ERROR', 'Token is invalid' ];
                    console.log( `AuthorizeToken - refresh token - here userName = ${ payload.userData }` );
                    return [ 'Success', payload.userData ];
                } );
            default:
                return [ 'Error', 'Please provide a token type' ]
        }
    }
}

In another function, I am calling as follows


const result = authorizeToken( req, 'REFRESH TOKEN' );
//result is undefined;

I am failing to get the array returned in the first and second case statements. With this code, it goes directly to the default:. If I add break; statements, nothing is returned. The only thing that seems to work smoothly is adding a let result; statement before the switch and then instead of returning inside the cases, I simply assign result to the array to be returned. Thereafter, I return result after the switch.

Cacious
  • 137
  • 1
  • 14
  • 2
    Try to put return behind jwt. Verify. – Mukarram Ishaq Jul 02 '20 at 16:52
  • This is not a `switch...case...` problem. The `.verify()` method is an asynchronous function (noticable on the callback, the function you pass as the last argument). – Andreas Jul 02 '20 at 16:58
  • not optimal code, I would either go for an object pattern that returns functions and catch the default case upfront or second option stick with the ugly switch, but at least define the values for jwt.verify with the switch and then call the jwt.verify with the altered values – Julian Kleine Jul 02 '20 at 17:03
  • @ Julian, I like your second idea about using the switch to alter the jwt.verify values then calling the jwt.verify with altered values. However, if I still wanted to do it this way, how do I make sure the value is returned? – Cacious Jul 02 '20 at 17:17
  • @Andreas You're right that it is an asynchronous function with the callback. Therefore, how do I alter my code to still return the inside the jwt.verify function? If I put an `async` right before the callback, which asynchronous action inside the function do I `await`? – Cacious Jul 02 '20 at 17:21

0 Answers0