NestJs: Import service from another module

Viewed 1110

I'm trying to use the surveyService in the voteOptionRepository, but when I use the route, the console return this: TypeError: this.surveyService.getSurveyById is not a function

This is my SurveyModule

    @Module({
    imports: [
        TypeOrmModule.forFeature([SurveyRepository]),
        AuthModule
    ],
    controllers: [SurveyController],
    providers: [SurveyService],
    exports: [SurveyService]
})

export class SurveyModule{}

This is my voteOptionModule

@Module({
    imports: [
        TypeOrmModule.forFeature([VoteOptionRepository]),
        AuthModule,
        SurveyModule
    ],
    controllers: [VoteOptionController],
    providers: [VoteOptionService]
})

export class VoteOptionModule{}

And this is how I'm trying to use the service

@EntityRepository(VoteOption)
export class VoteOptionRepository extends Repository<VoteOption>{
    constructor(private surveyService: SurveyService){
        super();
    }

    async createVoteOption(createVoteOptionDTO: CreateVoteOptionDTO, surveyId: number, user: User){
        const survey = await this.surveyService.getSurveyById(surveyId, user)
        const { voteOptionName, image } = createVoteOptionDTO;
        
        const voteOption = new VoteOption();

        voteOption.voteOptionName = voteOptionName;
        voteOption.image = image;
        voteOption.survey = survey;

        try{
            await voteOption.save()
            this.surveyService.updateSurveyVoteOptions(voteOption, surveyId, user)
        } catch(error){
            throw new InternalServerErrorException();
        }

        delete voteOption.survey;

        return voteOption;
    }
}
2 Answers

TypeORM repository classes do not adhere to Nest's Dependency Injection System, due to being tied TypeORM. Repository classes are actually supposed to have connections and entity managers passed to them in the constructor to allow for communication with the database. If you need logic from other services, you should generally be calling those other services from inside the service call, not the repository.

I'm new to NestJS, but I believe this is what you want to do. You need to inject the reference to your table in your service.

export class VoteOptionRepository extends Repository<VoteOption>{
    constructor(
       private surveyService: SurveyService
       @InjectRepository
       surveyServiceRepo(SurveyRepository)
      ){
        super();
      }

      async getSurveyById () {
        const survey = await this.surveyServiceRepo.find({id: 'survey-id'})
        return survey
     }
   }

Without seeing your SurveyService though, it may be that getSurveyById has not been defined properly, which is why your getting an error that it's not a function.

Related