refactor(OTP): simplify code by using upsert() #1283
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
The code for
sendEmailOtp()
andsendSmsOtp()
have a behaviour of find-then-create-or-update. However that not done in a transaction, and is not sync-safe.Sequelize has
findOrCreate()
which does create transaction by default, so we can just use that instead.Additionally the method
createOtpEntry()
is not very useful since there are 2 code path which are conditional on the otp types, and these are already distinct in the methodssendEmailOtp()
andsendSmsOtp()
themselves.Also there was one possible issue (not sure): The 2 OTP methods did not have the same behaviour to reset the OTP expiry (only the email OTP would reset the expiry). I'm not sure if it's on purpose or not, so it's worth having someone commenting on it. I'll start a thread in the PR to indicate the potential issue.
Solution
upsert()
as neededcreateOtpEntry()
Verified on staging (sample trace here)
Tests