Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 37 ยท Performance and Patterns

Repository and Unit of Work

Structure ORM code with repositories and a unit of work: Active Record versus Data Mapper, a service layer and one transaction boundary per use case.

When a project grows, queries creep into controllers, models and utility files. Soon nobody knows where "find the active users with unpaid invoices" lives, transactions are started in five places and a test needs the whole application to run. Two classic patterns put order back: the repository, which owns the queries for one kind of thing, and the unit of work, which owns one transaction for one use case.

In this lesson you will compare the two styles the ORMs give you, then build both patterns in a small runnable example on node:sqlite. TypeORM and Sequelize snippets are read-only.

Active Record versus Data Mapper

Active Record Data Mapper
Idea The model object saves and queries itself Plain objects; a separate repository persists them
Sequelize Natural fit: User.findAll(), user.save() Possible, with extra layers
TypeORM Supported: entities extend BaseEntity Default: dataSource.getRepository(User)
Strength Very little code, fast to start Domain objects stay free of database code; easier to test
Risk Models grow to mix data and logic; static calls are hard to fake More files and indirection

Neither is wrong. A small CRUD app does well with Active Record. A system with real business rules benefits from Data Mapper, where a User is just data and a UserRepository knows SQL.

TypeScript
// TypeORM Data Mapper style
const users = dataSource.getRepository(User);
const ada = await users.findOneBy({ email: '[email protected]' });

// TypeORM custom repository: wrap the queries you reuse
export const UserRepository = dataSource.getRepository(User).extend({
  findActiveByCountry(country: string) {
    return this.find({ where: { country, active: true }, order: { name: 'ASC' } });
  },
});
JavaScript
// Sequelize: a static method plays the same role
class User extends Model {
  static findActiveByCountry(country) {
    return this.findAll({ where: { country, active: true }, order: [['name', 'ASC']] });
  }
}

The key rule for both: a query with a name belongs in one place. The service calls users.findActiveByCountry('DE') and never builds the where object itself.

A repository, runnable

This stand-in repository takes its connection from outside. That detail is what makes a unit of work possible.

Node.js Repositories that share a connection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The unit of work

A unit of work tracks everything a use case changes and commits it as one transaction. In practice that means a small object that opens the transaction, hands out repositories bound to the same connection and either commits or rolls back at the end. TypeORM's EntityManager inside dataSource.transaction(...) and Sequelize's transaction t play this role; the pattern puts a name and a shape on it.

Node.js A unit of work with commit and rollback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The second checkout inserted a user, then the stock update broke the check. The unit of work rolled back, so Grace never exists. Without it, you would have a user row with no order.

Where to put the transaction boundary

  • In the service (use case) layer, not in repositories. A repository method like insert must not commit; it does not know what else belongs to the same business operation.
  • One use case, one unit of work, started at the entry point (a controller or message handler).
  • Pass the unit of work (or the entity manager) down. Do not reach for a global data source inside a repository, or the call silently leaves the transaction.

In TypeORM an easy way to express that is a repository factory:

TypeScript
const repos = (m: EntityManager) => ({
  users: m.getRepository(User),
  orders: m.getRepository(Order),
});

await dataSource.transaction(async (m) => {
  const { users, orders } = repos(m);
  const user = await users.save({ name: 'Ada' });
  await orders.save({ userId: user.id, cents: 500 });
});

Testing benefits

Because the service only talks to repositories, you can test it against fakes (see Factories and Mocks) and test each repository once against a real database (Testing Queries with node:test).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a repository's responsibility?

    Repositories keep named queries in one place; the use case decides the transaction boundary.
  2. 2. Which style does TypeORM use by default?

    TypeORM supports both, but repositories (Data Mapper) are the default.
  3. 3. Why must repositories in one use case share a connection?

    A transaction lives on one connection; repositories on other connections would escape it.
  4. 4. Where should the transaction boundary normally be?

    Only the use case knows which operations belong together.

Summary

  • Active Record is quick for small apps; Data Mapper keeps domain code clean and testable.
  • Give each reused query a name inside a repository.
  • A unit of work opens one transaction per use case and hands its repositories the same connection.
  • Put the boundary in the service layer and pass the transaction down explicitly.

Next: Connection Pooling and Caching