简体   繁体   English

NestJs:如何在实体侦听器中访问数据库?

[英]NestJs: How to access database in entity listeners?

I've got a @BeforeInsert() listener in my Post entity. 我的Post实体中有一个@BeforeInsert()侦听器。 The listener is supposed to create a unique slug for the slug column before insertion. 侦听器应该在插入之前为slug列创建唯一的子弹。

For example: 例如:

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?
    }
}

Since the slug column is supposed to be unique, I will have to check in the database to know whether the same slug already exists. 由于slug列应该是唯一的,因此我将必须在数据库中检查是否已经存在相同的段子。 If the slug already exists, I will then need to append a number behind the slug, like hello-word-1 . 如果该段子已经存在,则需要在该段子后附加一个数字,例如hello-word-1

However, to do so, I will need to access the Post repository of the entity in the Post entity class before I can access the database. 但是,为此,我需要先访问Post实体类中的实体的Post存储库,然后才能访问数据库。 But I don't see how I can inject the repository into my Post entity class to access the database for this purpose. 但是我看不到如何将存储库注入到Post实体类中以为此目的访问数据库。

How should I approach this problem? 我应该如何解决这个问题?

As far as I know it's not possible to use dependency injection in typeorm entities, since they are not instantiated by nest. 据我所知,不可能在typeorm实体中使用依赖注入,因为它们不是由nest实例化的。 You can however use an EntitySubscriber instead which can inject dependencies. 但是,您可以改为使用EntitySubscriber来注入依赖项。 See the solution from this Github issue : 请参阅此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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM