How can I select this
entity in when creating a repository method in typeorm?
I am trying to select password property on Admin entity but this
selects Repository not entity
@EntityRepository(Admin)
export class AdminRepository extends Repository<Admin> {
async comparePasswords(password: string): Promise<boolean> {
return await compare(password, this.password);
}
}
When you create a custom repository like this:
admin.repository.ts
@EntityRepository(Admin)
export class AdminRepository extends Repository<Admin> {}
You can use it, for example, in a service or controller (or other class) by injecting it on the constructor like this:
admin.service.ts
@Injectable()
export class AdminService {
constructor(
@InjectRepository(AdminRepository)
private adminRepository: AdminRepository,
) {}
async findAdminByName(name: string): Promise<boolean> {
return await = this.adminRepository.findOne({name});
}
}
But if you don't actually need to implement custom methods on repository class (take a look to all standard TypeOrm repository methods), you can achieve the same result without creating the custom repository file admin.repository.ts
, and injecting it on the fly directly on a service:
admin.service.ts
@Injectable()
export class AdminService {
constructor(
@InjectRepository(Admin)
private adminRepository: Repository<Admin>,
) {}
async findAdminByName(name: string): Promise<boolean> {
return await = this.adminRepository.findOne({name});
}
}
Take a look also to the doc Repository Pattern