DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Importance of Transit Gateway in Anypoint Platform
  • Load-Balancing Minecraft Servers with Kong Gateway
  • Application Retirement Using Informatica Data Archive
  • An Overview of Health Check Patterns

Trending

  • Efficient API Communication With Spring WebClient
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • SaaS in an Enterprise - An Implementation Roadmap
  • Go 1.24+ Native FIPS Support for Easier Compliance
  1. DZone
  2. Data Engineering
  3. Databases
  4. How to Perform a NestJS TypeORM Transaction Using QueryRunner?

How to Perform a NestJS TypeORM Transaction Using QueryRunner?

In this post, we will look at how to perform a NestJS TypeORM Transaction using the TypeORM QueryRunner class with examples.

By 
Saurabh Dashora user avatar
Saurabh Dashora
DZone Core CORE ·
Oct. 31, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
9.2K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, we will look at how to perform a NestJS TypeORM Transaction using the TypeORM QueryRunner class. This is also the recommended way of handling transactions in NestJS.

If you are new to using TypeORM with NestJS, refer to this detailed post about NestJS TypeORM Integration.

1. The Need for Transaction Management

Transactions are one of the most important concepts while dealing with databases. Basically, a transaction is a unit of work. We should treat it as a whole. Either it happens completely or it does not happen.

For example, you can think of transferring money from one account to another. At face value, this process involves multiple steps such as withdrawing money from the first account and then transferring it into the recipient’s account. The transfer fails if even one of the steps fails. Hence, we should handle such operations in the form of transactions.

2. The ACID Property of Transactions

A transaction must have the below properties. They are commonly known as ACID properties.

  • Atomicity — This means that the operations in a transaction are a single unit that succeeds or fails.
  • Consistency — A valid transaction brings the database from one valid state to another.
  • Isolation — Transactions should be isolated. In other words, transactions can occur concurrently. Basically, valid transactions don’t cause an inconsistent state. Also, the intermediate state of transaction should be invisible to other transactions.
  • Durability — Changes made by a transaction should be durable. In other words, the changes should survive even a system failure.

3. Handling NestJS TypeORM Transactions

The TypeORM package comes with the Connection class. We will inject this class into our LibraryService example.

See below code:

library.service.tsconstructor(
@InjectRepository(Book)
    private bookRepository: Repository<Book>,
    private connection: Connection
){}


The Connection class resides in the typeorm package. The below import statement will be needed.

import { Connection } from "typeorm";


The Connection object does not represent a single database connection. It basically points to a pool of connections. To refer to a single database collection, we use the QueryRunner class. Basically, every instance of the QueryRunner is a connection.

4. Using QueryRunner Class

We can now use the Connection object to create a transaction.

See the below example:

async createMultipleBooks(books: Book[]) {
   const queryRunner = this.connection.createQueryRunner();

        await queryRunner.connect();
        await queryRunner.startTransaction();

        try {
            await queryRunner.manager.save(books[0]);
            await queryRunner.manager.save(books[1]);

            await queryRunner.commitTransaction();
        }catch (err) {
            await queryRunner.rollbackTransaction();
        }finally {
            await queryRunner.release();
        }
}


Basically, we use an instance of QueryRunner to establish a connection and start a transaction. Then, we save all the books (in this case 2 books) as part of the same transaction. If something goes wrong, we rollback everything. Else, we commit the transaction and release the connection.

Conclusion

With this, we are done with NestJS TypeORM Transaction using QueryRunner. You can find the code for the same on Github.

If you have any comments or queries about the post, please feel free to write in the comments section below.

Database Connection (dance)

Published at DZone with permission of Saurabh Dashora. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Importance of Transit Gateway in Anypoint Platform
  • Load-Balancing Minecraft Servers with Kong Gateway
  • Application Retirement Using Informatica Data Archive
  • An Overview of Health Check Patterns

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!