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
.