api-monetization-demo
api-monetization-demo copied to clipboard
Fixing generateAPIKey return value
#1
Function generateAPIKey()
wouldn't return expected value in case of already existing key, it would return undefined
.
Even TypeScript complains about that: "Not all code paths return a value. (7030)"
Comparison with simulation of duplicate keys:
// Previous
const generateAPIKey = () => {
const apiKey = randomBytes(16).toString('hex');
const hashedAPIKey = hashAPIKey(apiKey);
const pass = Math.random();
console.log(pass);
if (pass > 0.05) {
generateAPIKey();
} else {
return { hashedAPIKey, apiKey };
}
}
console.log(generateAPIKey());
/* outputs:
0.6816072520636933
0.9997633555045544
0.135031872947307
0.7001910464410104
0.04146693961505621
undefined
*/
// Fixed
const generateAPIKey = () => {
const apiKey = randomBytes(16).toString('hex');
const hashedAPIKey = hashAPIKey(apiKey);
const pass = Math.random();
console.log(pass);
if (pass > 0.05) {
return generateAPIKey();
} else {
return { hashedAPIKey, apiKey };
}
}
console.log(generateAPIKey());
/* outputs:
0.45902566558983326
0.9184364490695001
0.2621821004468128
0.1388316804274583
0.24552862267388997
0.31256345535196006
0.014334729620895104
{
hashedAPIKey: 'e357892f569ed19b7c9212e65388e1bc319fb1bd9c3010d4c25c67c8de77af5d',
apiKey: 'b4646c567e38de2371960fcfbbf4a296'
}
*/
inb4
fixes missing
return
writes a xxx long PR description 😅
When?