admin管理员组文章数量:1287828
I'm working on building an API for a small hackathon project. It will be a platform for teachers to share lesson plans for students.
I created my first table, Subject, to store lesson subjects like math, science, etc. and I'm now creating a second table SubSubject (I'm not crazy about the name either) for sub-genres (ex. Science would include biology, chemistry, etc.).
I'm using typeorm for generating migrations and have already created and run the first migration to create the Subject table. I then created the entity for SubSubject and modified the Subject entity to include the relationship between the two tables.
My problem now is that I've updated the modules to include the entities and forwardRefs to try to resolve the circular dependency, but it doesn't solve that error about one entity (in my case, the SubjectEntity) not being accessed before initialization. I assumed from reading the documents that a fix would be as simple as adding a forwardRef to each entity's module, but that doesn't seem to be the case.
I'm wondering if there's something fundamental that I'm not understanding about how the forwardRef works, so any explanation to help with future debugging is appreciated. I also have read several other SO posts about resolving circular dependencies, and many of them seem to imply that if you're needing to fix a circular dependency, there's a code smell there. Should I not be establishing the ManyToOne and OneToMany on each side? Is there a simpler way that I should be establishing these relations between tables? Some of the articles I read were more related to service dependencies being circular, but I'm just trying to establish table relationships here.
Here are entity and module files so far, since they're pretty small:
Subject Module:
import { forwardRef, Module } from '@nestjs/common';
import { SubjectEntity } from './subject.entity.js';
import { SubjectController } from './subject.controller.js';
import { SubjectService } from './subject.service.js';
import { SubSubjectModule } from '../sub-subject/sub-subject.module.js';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forFeature([SubjectEntity]),
forwardRef(() => SubSubjectModule),
],
controllers: [SubjectController],
providers: [SubjectService],
})
export class SubjectModule {}
Subject Entity:
import { BaseEntity } from '../../utils/base.entity.js';
import { SubSubjectEntity } from '../sub-subject/sub-subject.entity.js';
@Entity('subject')
@Unique(['name'])
export class SubjectEntity extends BaseEntity {
@Column({ type: 'varchar', length: 100 })
name: string;
@OneToMany(() => SubSubjectEntity, (subSubject) => subSubject.subject)
subSubjects: SubSubjectEntity[];
}
SubSubjectModule:
import { forwardRef, Module } from '@nestjs/common';
import { SubSubjectService } from './sub-subject.service.js';
import { SubSubjectEntity } from './sub-subject.entity.js';
import { SubjectModule } from '../subject/subject.module.js';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forFeature([SubSubjectEntity]),
forwardRef(() => SubjectModule),
],
providers: [SubSubjectService],
exports: [SubSubjectService],
})
export class SubSubjectModule {}
SubSubjectEntity:
import { Entity, Column, Unique, ManyToOne, JoinColumn } from 'typeorm';
import { BaseEntity } from '../../utils/base.entity.js';
import { SubjectEntity } from '../subject/subject.entity.js';
@Entity('sub_subject')
@Unique(['name'])
export class SubSubjectEntity extends BaseEntity {
@Column({ type: 'varchar', nullable: false, length: 100 })
name: string;
@ManyToOne(() => SubjectEntity, (subject) => subject.subSubjects, {
onDelete: 'RESTRICT',
nullable: false,
})
@JoinColumn({ name: 'subject_id' })
subject: SubjectEntity;
}
I have tried removing the entity import from each and that temporarily allowed the API to run locally, but then I was unable to run my migration command and received the same error:
ReferenceError: Cannot access 'SubjectEntity' before initialization
I also considered that maybe the forwardRef is only needed in one file or the other, and that having it in both places was repeating the circular dependency I was trying to fix, but I tried removing it from each module and that did not resolve the issue either.
I'm working on building an API for a small hackathon project. It will be a platform for teachers to share lesson plans for students.
I created my first table, Subject, to store lesson subjects like math, science, etc. and I'm now creating a second table SubSubject (I'm not crazy about the name either) for sub-genres (ex. Science would include biology, chemistry, etc.).
I'm using typeorm for generating migrations and have already created and run the first migration to create the Subject table. I then created the entity for SubSubject and modified the Subject entity to include the relationship between the two tables.
My problem now is that I've updated the modules to include the entities and forwardRefs to try to resolve the circular dependency, but it doesn't solve that error about one entity (in my case, the SubjectEntity) not being accessed before initialization. I assumed from reading the documents that a fix would be as simple as adding a forwardRef to each entity's module, but that doesn't seem to be the case.
I'm wondering if there's something fundamental that I'm not understanding about how the forwardRef works, so any explanation to help with future debugging is appreciated. I also have read several other SO posts about resolving circular dependencies, and many of them seem to imply that if you're needing to fix a circular dependency, there's a code smell there. Should I not be establishing the ManyToOne and OneToMany on each side? Is there a simpler way that I should be establishing these relations between tables? Some of the articles I read were more related to service dependencies being circular, but I'm just trying to establish table relationships here.
Here are entity and module files so far, since they're pretty small:
Subject Module:
import { forwardRef, Module } from '@nestjs/common';
import { SubjectEntity } from './subject.entity.js';
import { SubjectController } from './subject.controller.js';
import { SubjectService } from './subject.service.js';
import { SubSubjectModule } from '../sub-subject/sub-subject.module.js';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forFeature([SubjectEntity]),
forwardRef(() => SubSubjectModule),
],
controllers: [SubjectController],
providers: [SubjectService],
})
export class SubjectModule {}
Subject Entity:
import { BaseEntity } from '../../utils/base.entity.js';
import { SubSubjectEntity } from '../sub-subject/sub-subject.entity.js';
@Entity('subject')
@Unique(['name'])
export class SubjectEntity extends BaseEntity {
@Column({ type: 'varchar', length: 100 })
name: string;
@OneToMany(() => SubSubjectEntity, (subSubject) => subSubject.subject)
subSubjects: SubSubjectEntity[];
}
SubSubjectModule:
import { forwardRef, Module } from '@nestjs/common';
import { SubSubjectService } from './sub-subject.service.js';
import { SubSubjectEntity } from './sub-subject.entity.js';
import { SubjectModule } from '../subject/subject.module.js';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forFeature([SubSubjectEntity]),
forwardRef(() => SubjectModule),
],
providers: [SubSubjectService],
exports: [SubSubjectService],
})
export class SubSubjectModule {}
SubSubjectEntity:
import { Entity, Column, Unique, ManyToOne, JoinColumn } from 'typeorm';
import { BaseEntity } from '../../utils/base.entity.js';
import { SubjectEntity } from '../subject/subject.entity.js';
@Entity('sub_subject')
@Unique(['name'])
export class SubSubjectEntity extends BaseEntity {
@Column({ type: 'varchar', nullable: false, length: 100 })
name: string;
@ManyToOne(() => SubjectEntity, (subject) => subject.subSubjects, {
onDelete: 'RESTRICT',
nullable: false,
})
@JoinColumn({ name: 'subject_id' })
subject: SubjectEntity;
}
I have tried removing the entity import from each and that temporarily allowed the API to run locally, but then I was unable to run my migration command and received the same error:
ReferenceError: Cannot access 'SubjectEntity' before initialization
I also considered that maybe the forwardRef is only needed in one file or the other, and that having it in both places was repeating the circular dependency I was trying to fix, but I tried removing it from each module and that did not resolve the issue either.
Share Improve this question edited Feb 22 at 23:26 Paul T. 4,91712 gold badges47 silver badges63 bronze badges asked Feb 22 at 20:53 AllisonAllison 311 silver badge7 bronze badges1 Answer
Reset to default 0Ensure that your services are not causing circular dependencies. If your SubjectService
depends on SubSubjectService
and vice versa, you might need to use forwardRef
in the service providers as well. Have you tried this?
@Injectable()
export class SubjectService {
constructor(
@Inject(forwardRef(() => SubSubjectService))
private readonly subSubjectService: SubSubjectService,
) {}
}
本文标签:
版权声明:本文标题:typeorm - What is the best practice for avoiding (or handling) circular dependency in NestJS when needed for table relationships 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741327127a2372552.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论