One query that arises is regarding the @EntityRepository
decorator becoming deprecated in typeorm@^0.3.6
. What is now the recommended or TypeScript-friendly approach to creating a custom repository for an entity in NestJS? Previously, a custom repository would be structured like this:
// users.repository.ts
import { EntityRepository, Repository } from 'typeorm';
import { User } from './user.entity';
@EntityRepository(User)
export class UsersRepository extends Repository<User> {
async createUser(firstName: string, lastName: string): Promise<User> {
const user = this.create({
firstName,
lastName,
});
await this.save(user);
return user;
}
}
Since NestJS inherently supports TypeScript, calling usersRepository.createUser()
in a service like below should work seamlessly:
// users.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './user.entity';
import { UsersRepository } from './users.repository';
@Injectable()
export class UsersService {
constructor(
@InjectRepository(UsersRepository)
private readonly usersRepository: UsersRepository,
) {}
async createUser(firstName: string, lastName: string): Promise<User> {
return this.usersRepository.createUser(firstName, lastName);
}
}
The custom repository would be imported into modules as shown below:
// users.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersController } from './users.controller';
import { UsersRepository } from './users.repository';
import { UsersService } from './users.service';
@Module({
imports: [TypeOrmModule.forFeature([UsersRepository])],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}
My mention of MongoDB stems from the experience of encountering an error while using
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="70040900151f021d30405e42">[email protected]</a>
, where @EntityRepository
is still supported. However, upon attempting to import it in the module, I faced an error stating Repository not found
or similar. Interestingly, this issue was not present when configuring TypeORM with postgresql
. After discovering the deprecation of @EntityRepository
, I couldn't find any relevant examples in the NestJS documentation.