我在两个实体:ManyToMany
和VideoEntity
之间有一个GroupEntity
关系。每当创建或删除该关系之一时,我都想通过EntitySubscriber
发出的websocket事件通知客户端。
@Entity({ name: 'videos' })
export class VideoEntity {
@PrimaryGeneratedColumn()
id: number;
@ManyToMany(
() => VideoGroupEntity,
g => g.videos,
)
groups: VideoGroupEntity[];
}
@Entity({ name: 'video-groups' })
export class VideoGroupEntity {
@PrimaryGeneratedColumn()
id: number;
@ManyToMany(
() => VideoEntity,
v => v.groups,
)
@JoinTable({
name: 'video-group-joins',
joinColumn: { name: 'videoId' },
inverseJoinColumn: { name: 'groupId' },
})
videos: VideoEntity[];
}
我已经使用TypeORM了很多,尤其是在NestJS上,但是还没有找到正确的方法来进行设置。没有关于联接表事件的文档,也没有关于使用手动定义的实体作为联接表的文档。
这是我想出的加入实体:
@Entity({ name: 'video-group-joins' })
export class VideoGroupJoinEntity {
@PrimaryColumn()
videoId: number;
@PrimaryColumn()
groupId: number;
}
这是它的订户(NestJS实现):
@Injectable()
export class VideoGroupJoinsSubscriber implements EntitySubscriberInterface<VideoGroupJoinEntity> {
constructor(
@InjectConnection() readonly connection: Connection,
) {
connection.subscribers.push(this);
}
listenTo() {
return VideoGroupsJoinEntity;
}
afterInsert(event: InsertEvent<VideoGroupJoinEntity>) {
// This is where I plan to emit the relation creation event
console.log(event); // Seems to be working as expected
}
afterRemove(event: RemoveEvent<VideoGroupJoinEntity>) {
// This is where I plan to emit the relation deletion event
console.log(event); // event.entity is always undefined
}
}
如您在VideoGroupJoinsSubscriber
注释中所见,RemoveEvent
实体始终为undefined
。这就是让我认为我的工具有问题的原因。
这里有人遇到过相同的用例吗?您找到合适的实现了吗?