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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Database Connection Pooling at Scale: PgBouncer + Multi-Tenant Postgres (10K Concurrent Connections)
  • Importance of Transit Gateway in Anypoint Platform
  • Load-Balancing Minecraft Servers with Kong Gateway
  • The Query Takes 20 ms. Why Does the API Take Two Seconds?

Trending

  • How You Clear Your HTML5 Canvas Matters
  • Deploying Small Language Models on Sovereign Cloud
  • LangChainGo vs Genkit Go: Where Genkit Shines
  • Building Enterprise-Grade Real-Time IoT Dashboards with Vue 3, MQTT, and Kafka

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
DZone Core CORE ·
Oct. 31, 21 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
9.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Database Connection Pooling at Scale: PgBouncer + Multi-Tenant Postgres (10K Concurrent Connections)
  • Importance of Transit Gateway in Anypoint Platform
  • Load-Balancing Minecraft Servers with Kong Gateway
  • The Query Takes 20 ms. Why Does the API Take Two Seconds?

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook