Skip to content

Instantly share code, notes, and snippets.

@imkrish
Last active April 18, 2020 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imkrish/c0211bb221b5853667c34f7b4093e608 to your computer and use it in GitHub Desktop.
Save imkrish/c0211bb221b5853667c34f7b4093e608 to your computer and use it in GitHub Desktop.
@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