[英]NestJs: How to access database in entity listeners?
我的Post
实体中有一个@BeforeInsert()
侦听器。 侦听器应该在插入之前为slug
列创建唯一的子弹。
例如:
export class Post extends BaseEntity {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
slug: string
@BeforeInsert()
private updateSlug() {
this.slug = slugify(this.title)
// I will need to access the database to check whether the same slug has existsed already or not.
// How do I access the database in this listener method?
}
}
由于slug
列应该是唯一的,因此我将必须在数据库中检查是否已经存在相同的段子。 如果该段子已经存在,则需要在该段子后附加一个数字,例如hello-word-1
。
但是,为此,我需要先访问Post
实体类中的实体的Post
存储库,然后才能访问数据库。 但是我看不到如何将存储库注入到Post
实体类中以为此目的访问数据库。
我应该如何解决这个问题?
据我所知,不可能在typeorm实体中使用依赖注入,因为它们不是由nest实例化的。 但是,您可以改为使用EntitySubscriber来注入依赖项。 请参阅此Github问题的解决方案:
import { Injectable } from '@nestjs/common';
import { InjectConnection, InjectRepository } from '@nestjs/typeorm';
import { Connection, EntitySubscriberInterface, InsertEvent, Repository } from 'typeorm';
import { Post } from '../models';
@Injectable()
export class PostSubscriber implements EntitySubscriberInterface {
constructor(
@InjectConnection() readonly connection: Connection,
// Inject your repository here
@InjectRepository(Photo) private readonly postRepository: Repository<Post>,
) {
connection.subscribers.push(this);
}
listenTo() {
return Post;
}
beforeInsert(event: InsertEvent<Post>) {
// called before insert
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.