Last active
April 18, 2020 10:31
-
-
Save imkrish/c0211bb221b5853667c34f7b4093e608 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Post('money/transfer') | |
async transferMoney(@Body() dto: TransferMoneyDto) { | |
// Start session using mongo connection | |
const session = await this.mongoConnection.startSession(); | |
// Start transaction using the session | |
session.startTransaction(); | |
try { | |
// This method will do a few mongo db operations | |
const result = await this.transferMoneyService.transfer(dto, session); | |
// If transferMoneyService.transfer is resolved, we then commit the transaction | |
// This will do the actual writes/updates to the database | |
await session.commitTransaction(); | |
return result; | |
} catch (e) { | |
// If the error is thrown, we will abort the transaction, so nothing will be changed in the database | |
await session.abortTransaction(); | |
throw e | |
} finally { | |
// Make sure to end transaction session. | |
session.endSession(); | |
} | |
} | |
// The method that will update 2 Mongo documents | |
async transfer(dto: TransferMoneyDto, session: ClientSession) { | |
const { fromAccountId, transferAmount, toAccountId } = dto; | |
// Make sure to put session in the query options | |
await this.accountModel.findByIdAndUpdate(fromAccountId, { $inc: { amount: -1 * transferAmount } }, { session }).exec() | |
await this.accountModel.findByIdAndUpdate(toAccountId, { $inc: { amount: +1 * transferAmount }}, { session }).exec() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment