【问题标题】:NestJs: How to access database in entity listeners?NestJs:如何在实体监听器中访问数据库?
【发布时间】:2019-04-15 07:54:29
【问题描述】:

我的Post 实体中有一个@BeforeInsert() 监听器。侦听器应该在插入之前为 slug 列创建一个唯一的 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 列应该是唯一的,我必须检查数据库以了解是否已经存在相同的 slug。如果 slug 已经存在,那么我需要在 slug 后面附加一个数字,例如 hello-word-1

但是,为此,我需要先访问Post 实体类中实体的Post 存储库,然后才能访问数据库。但我不知道如何将存储库注入到我的Post 实体类中以访问数据库。

我应该如何解决这个问题?

【问题讨论】:

  • 您不应该从您的实体访问存储库,但您可以在自定义存储库中提供一个 API 来执行您需要的操作,因为您可以从那里获取实体管理器。然后,您只需在需要时从代码库中调用存储库。在插入之前检查 slug 在我看来为时已晚,这是您应该事先做的事情。

标签: javascript node.js typescript nestjs typeorm


【解决方案1】:

据我所知,不可能在 typeorm 实体中使用依赖注入,因为它们不是通过嵌套实例化的。但是,您可以使用 EntitySubscriber 代替它可以注入依赖项。从这个Github issue查看解决方案:

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

}

【讨论】:

  • 我怎样才能注入任何服务?此示例仅使用@InjectConnection@InjectRepository。我试过@Inject() public myService MyService,但结果是undefined
  • 您是否尝试将 PostSubscriber class 添加到模块的 providers 数组中?
猜你喜欢
  • 1970-01-01
  • 2012-02-08
  • 1970-01-01
  • 2012-09-19
  • 2017-01-12
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
相关资源
最近更新 更多