0
0
NestJSframework~5 mins

Repository pattern in NestJS

Choose your learning style9 modes available
Introduction

The Repository pattern helps organize how your app talks to the database. It keeps data access code separate and easy to manage.

When you want to keep database code separate from business logic.
When you need to switch databases without changing your app logic.
When you want to write cleaner, easier-to-test code for data access.
When working on a team to keep data handling consistent.
When you want to reuse data access methods across different parts of your app.
Syntax
NestJS
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';

@Injectable()
export class UserRepository {
  constructor(
    @InjectRepository(User)
    private readonly repo: Repository<User>,
  ) {}

  // Custom methods here
}

Create an @Injectable() class and inject Repository<Entity> using @InjectRepository.

Add custom data access methods using the injected repository.

Examples
This example adds a custom method to find a user by name.
NestJS
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';

@Injectable()
export class UserRepository {
  constructor(
    @InjectRepository(User)
    private readonly repo: Repository<User>,
  ) {}

  findByName(name: string) {
    return this.repo.findOne({ where: { name } });
  }
}
This shows how to inject a repository into a service to use its methods.
NestJS
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  findAll() {
    return this.userRepository.find();
  }
}
Sample Program

This example shows a simple repository class in NestJS using TypeORM. It has methods to create a user and find a user by email.

NestJS
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';

@Injectable()
export class UserRepository {
  constructor(
    @InjectRepository(User)
    private readonly repo: Repository<User>,
  ) {}

  async findByEmail(email: string) {
    return await this.repo.findOne({ where: { email } });
  }

  async createUser(name: string, email: string) {
    const user = this.repo.create({ name, email });
    return await this.repo.save(user);
  }
}

// Usage example (inject into a service or controller):
// constructor(private userRepository: UserRepository) {}
// await userRepository.createUser('Alice', 'alice@example.com');
// const user = await userRepository.findByEmail('alice@example.com');
// console.log(user);
OutputSuccess
Important Notes

In NestJS with TypeORM, you often inject repositories using @InjectRepository.

Keep repository methods focused on data access only.

Use async/await to handle database calls cleanly.

Summary

The Repository pattern separates data access from app logic.

It makes your code cleaner and easier to test.

In NestJS, repositories are usually injected into services for use.