1
votes

On a NestJS API, I would like to use a module service into an entity to populate this entity with non-database attributes.

In my case, I want to get the number of articles of the category I am retrieving.

@Entity({ name: 'categories' })
export class Category {
    constructor(private readonly service: CategoriesService) { }

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    @Index({ unique: true })
    title: string;

    @OneToMany(() => Article, articles => articles.category)
    articles: Article[];

    numberOfExercices: number;

    @AfterLoad()
    async countExercices() {
        this.numberOfExercices = await this.service.getNumberOfArticles(this.id);
    }
}

But I get this error :

Nest can't resolve dependencies of the GlobalPrevCategoriesService (GlobalPrevCategoriesRepository, ?).
Please make sure that the argument dependency at index [1] is available in the GlobalPrevCategoriesModule context.

I tried this little variant but I get the same error.

constructor(
    @Inject(GlobalPrevCategoriesService)
    private readonly service: GlobalPrevCategoriesService) { }
)

Here is my module:

@Module({
    imports: [
        TypeOrmModule.forFeature([CategoriesRepository]),
        ArticlesModule
    ],
    controllers: [CategoriesController],
    providers: [CategoriesService],
    exports: [CategoriesService]
})
export class CategoriesModule { }

Is using a service into a entity even possible ?

1

1 Answers

2
votes

I think it is not possible to inject services into the entities. The ORM module (for example, TypeORM) instantiates entities. And ORMs are not aware of the dependency injection mechanism in the NestJs framework.

You can check the Active-Record pattern in the TypeORM. It solves your problem to get the number of articles related to a category instance after load. But it does not help you to inject CategoriesService into your Category entity.

In general, it is not a good idea to inject service classes into the entity classes.