Answer the question
In order to leave comments, you need to log in
How to refactor this code?
How can you prevent code duplication with an error?
I will be grateful for help
async login(email: string, password: string) {
const user = await User.findOne({ where: { email } })
if (!user) {
throw ApiError.BadRequest('Your email or password was entered incorrectly.')
}
const isPassEquals = await bcrypt.compare(password, user.password)
if (!isPassEquals) {
throw ApiError.BadRequest('Your email or password was entered incorrectly.')
}
const userDto = new UserDto(user)
const tokens = tokenService.generateTokens(userDto.id, userDto.email)
await tokenService.saveToken(userDto.id, tokens.refreshToken)
return { ...tokens, user: userDto }
}
Answer the question
In order to leave comments, you need to log in
For example, you can move the validation code into a separate function:
async findUserByEmailAndPassword(email: string, password: string): User {
const user = await User.findOne({ where: {email} });
if(user) {
const passwordValid = await bcrypt.compare(password, user.password);
if(passwordValid)
return user;
}
return null;
}
const user = await findUserByEmailAndPassword(email, password);
if(user === null)
throw ApiError.BadRequest('Your email or password was entered incorrectly.');
await bcrypt.compare(password, user.password)
drag it into if, but I don’t really like this option.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question