I wanted to double-check my thinking on using TypeScript in ExpressJS. Here's my abridged code in question:
/**
* Verifies that an email address exists in the DB.
* If so, sends them an email to recover their password.
*
* @param {Request} req
* @param {Response} res
*/
const sendPasswordRecoveryEmail = (req: Request, res: Response) => {
const email = req.body.email
const checkForEmailAddress = async (email: string) => {
return await pool.query(`SELECT password FROM users WHERE email = $1`, [email]);
};
const updatePasswordFields = async (password: string, newPassword: string, email: string) => {
return await pool.query(`UPDATE users SET last_password = $1, password = $2 WHERE email = $3`, [password, newPassword, email]);
};
const passwordRecoveryProcess = async (email: string) => {
try {
res.status(200).send({ status: true, message: 'Password recovery process initiated.' });
const results = await checkForEmailAddress(email);
if (results.rows.length === 1) {
const existingPassword = results.rows[0].password;
const newTempPassword = generateRandomPassword();
await updatePasswordFields(existingPassword, newTempPassword, email);
const body = `...`;
emailService({email, subject: 'MySite Password Recovery', body});
}
} catch (error) {
console.error('Error', error);
}
}
passwordRecoveryProcess(email); // Initiate async Password Recovery Process
};
With this line of code:
const results = await checkForEmailAddress(email);
I'm using await
before calling the function. Then within the function itself I'm also using async
/await
. Is this the correct practice or is there some redundancy with it?
async (args) => await expression
simplifies to(args) => expression
await
inreturn await pool.query(...)
. It does the same thing if you just doreturn pool.query()
. Either way, the function returns a promise.return await promise
andreturn promise