Hi,
I am currently experimenting with Nest and considering to use it for a new project. One of the requirements is support for atomic transaction. While it seems to be supported in Node/Mongoose I cannot find any examples of how transactions can be implemented using Nest/TypeScript. Gone through Nest documentation and couldn't find any examples either. Does anyone have any experience in implementing transactions using Nest?
I don't think that this is something that should be solved particularly by Nest. See mongoose docs https://mongoosejs.com/docs/transactions.html
I am using transactions in my project and look like this.
async createOrUpdateAdministrator(newAdmin: CreateUserDto) {
try {
const session = await this.userModel.db.startSession();
session.startTransaction();
try {
const adminHash = await this.hashPassword(newAdmin, Role.ADMIN);
const createdAdmin = await this.userModel.findOneAndUpdate(
{ role: Role.ADMIN }, adminHash, { upsert: true, new: true })
.session(session)
.select('-password')
.exec();
const accessToken = await this.generateToken(createdAdmin.toJSON());
await session.commitTransaction();
this.logger.info(`Administrator '${newAdmin.email}' created or updated`);
return accessToken;
} catch (error) {
await session.abortTransaction();
this.logger.error(`Administrator '${newAdmin.email}' couldn\'t create or update`);
this.logger.error(error);
} finally {
session.endSession();
}
} catch (error) {
this.logger.error(error);
this.logger.error('Transaction couldn\'t create');
}
}
Only need to take the db connection through the model and create a session.
do you know a way of using Promise.all in conjunction with transactions @silvelo ? Thanks for your solution!
do you know a way of using Promise.all in conjunction with transactions @silvelo ? Thanks for your solution!
No, sorry :( .
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
I am using transactions in my project and look like this.
Only need to take the db connection through the model and create a session.