如何将TypeORM通用Repository作为NestJS其他模块的Provider使用
问题分析与修正方案
一、先完善GenericRepository的update方法
原代码中update方法未实现实际更新逻辑,仅返回仓库实例,先补充完整:
import { Injectable } from '@nestjs/common' import { IGenericRepository } from '../abstracts/generic-repository' import { Repository } from 'typeorm' @Injectable() export class GenericRepository<T> implements IGenericRepository<T> { private _repository: Repository<T>; constructor(repository: Repository<T>) { this._repository = repository; } getAll(): Promise<T[]> { return this._repository.find() } findById(id: any): Promise<T> { return this._repository.findOneBy(id) } create(item: T): Promise<T> { return this._repository.save(item) } // 修正update方法,实现实际更新逻辑 async update(id: string, item: Partial<T>): Promise<T> { await this._repository.update(id, item); return this._repository.findOneBy({ id } as unknown as Record<string, any>); } }
二、修正UserModule的Provider配置
原配置存在3个核心错误:
- 错误尝试实例化参数名
genericRepository而非类本身 - 错误使用
Repository(user)获取仓库,NestJS需通过DI注入TypeORM生成的Repository<User>实例 - 错误注入
User实体本身,而非对应的仓库实例
正确配置方式
使用TypeORM提供的getRepositoryToken获取对应实体的仓库DI令牌,注入后实例化GenericRepository<User>:
import { Module } from '@nestjs/common'; import { User } from '../entity/user.entity'; import { GenericRepository } from '@app/common'; import { Repository, getRepositoryToken } from 'typeorm'; @Module({ providers: [ { provide: 'userGenericRepository', // 自定义注入令牌 useFactory: (userRepository: Repository<User>) => { return new GenericRepository<User>(userRepository); }, inject: [getRepositoryToken(User)], // 注入TypeORM为User实体创建的Repository } ], // 若需在其他模块使用,需导出该Provider exports: ['userGenericRepository'] }) export class UserModule { }
更优雅的优化:使用常量令牌
避免字符串硬编码,可在公共模块定义常量令牌:
// src/common/constants.ts export const USER_REPOSITORY = 'USER_REPOSITORY';
修改UserModule:
import { Module } from '@nestjs/common'; import { User } from '../entity/user.entity'; import { GenericRepository, USER_REPOSITORY } from '@app/common'; import { Repository, getRepositoryToken } from 'typeorm'; @Module({ providers: [ { provide: USER_REPOSITORY, useFactory: (userRepository: Repository<User>) => new GenericRepository<User>(userRepository), inject: [getRepositoryToken(User)], } ], exports: [USER_REPOSITORY] }) export class UserModule { }
三、在业务服务中使用该仓库
在UserService中注入并使用:
import { Injectable, Inject } from '@nestjs/common'; import { User } from '../entity/user.entity'; import { GenericRepository } from '@app/common'; import { USER_REPOSITORY } from '@app/common/constants'; @Injectable() export class UserService { constructor( @Inject(USER_REPOSITORY) private readonly userRepo: GenericRepository<User> ) {} async getAllUsers() { return this.userRepo.getAll(); } // 其他业务逻辑方法... }
内容的提问来源于stack exchange,提问作者morteza mortezaie
相关产品推荐
相关产品推荐

