Search code examples
nestjstypeorm

Nest.js project with TypeORM Active Record implementation


I'm trying to build a project with Nest.js and TypeORM. I like the Active Record approach in TypeORM

I define an entity as follows, with some static helper methods:

export class Book extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  description: string;

  static async createNew(attributes: BookDto): Promise<Book> {
    const entity = new Book();
    entity.name = attributes.name;
    entity.description = attributes.description;

    return entity.save();
  }

  static async findByName(name: string): Promise<Book> {
    return Book.findOne({
      where: { name },
    });
  }
}

I'm trying to follow the patterns in the Nest docs to inject it into my service:

@Injectable()
export class BookService {
  constructor(
    @InjectRepository(Book)
    private readonly bookRepository: Repository<Book>,
  ) {}

  async create(bookAttrs: BookDto): Promise<Book> {
    return Book.createNew(bookAttrs);
  }
}

But as you can see in my service, I am only using the static methods. In this case, do I even need to inject the dependencies? Is there a better pattern I should be following?


Solution

  • If you're following this approach, you don't need to inject the Repository in your service and you don't even have to import the TypeOrmModule.forFeature([User]) in your feature module since you're not injecting any TypeOrm related stuff because you're using (global) static methods that can be used anywhere.

    However, I cannot recommend doing so and the most important reason would be testing: Nest gives you a very convenient way of mocking dependencies in your tests. This is only possible because you declare your dependencies in your module and the injector decides what actual implementation is going to be used. When you have implicit dependencies by using static methods, it get's really hard to mock them in your unit and integration tests which in case of database access you definitely want to do.

    Besides testing, your dependencies might get messy when you have static access from anywhere. Having declarative dependencies in your modules is great for keeping your code clean.