0
0
NestjsHow-ToBeginner ยท 3 min read

How to Create Repository in NestJS: Step-by-Step Guide

In NestJS, create a repository by defining an entity and then injecting the repository using @InjectRepository from @nestjs/typeorm. This repository allows you to perform database operations cleanly within your service classes.
๐Ÿ“

Syntax

To create a repository in NestJS, you first define an entity class representing your database table. Then, inject the repository into your service using @InjectRepository(Entity). Use the repository methods to interact with the database.

  • Entity: Defines the database table structure.
  • @InjectRepository: Decorator to inject the repository.
  • Repository: Provides methods like find, save, delete.
typescript
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;
}

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

  findAll() {
    return this.userRepository.find();
  }
}
๐Ÿ’ป

Example

This example shows how to create a User entity and a UserService that uses the repository to fetch all users from the database.

typescript
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;
}

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

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

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  providers: [UserService],
  exports: [UserService],
})
export class UserModule {}
Output
When calling userService.findAll(), it returns a Promise resolving to an array of User objects from the database.
โš ๏ธ

Common Pitfalls

Common mistakes when creating repositories in NestJS include:

  • Not importing TypeOrmModule.forFeature([Entity]) in the module, so the repository is not registered.
  • Forgetting to decorate the entity class with @Entity().
  • Injecting the repository without @InjectRepository(Entity), which causes injection errors.
  • Trying to use repository methods before the database connection is established.
typescript
/* Wrong: Missing TypeOrmModule.forFeature import */
@Module({
  providers: [UserService],
})
export class UserModule {}

/* Right: Include TypeOrmModule.forFeature */
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  providers: [UserService],
})
export class UserModule {}
๐Ÿ“Š

Quick Reference

StepDescription
Define EntityCreate a class with @Entity() and columns.
Import RepositoryAdd TypeOrmModule.forFeature([Entity]) in module imports.
Inject RepositoryUse @InjectRepository(Entity) in service constructor.
Use RepositoryCall repository methods like find(), save(), delete().
โœ…

Key Takeaways

Always decorate your entity class with @Entity() to define the database table.
Import TypeOrmModule.forFeature([Entity]) in your module to register the repository.
Inject the repository in your service using @InjectRepository(Entity) for database access.
Use repository methods like find() and save() to interact with the database.
Ensure your database connection is configured and established before using repositories.