NodeJS 扩展多个类以包含来自其他实体的列在nestJS中不起作用

bkhjykvo  于 2023-03-22  发布在  Node.js
关注(0)|答案(1)|浏览(151)

我正在做一个嵌套项目,在那里我必须扩展我的实体类,以具有来自其他类的公共列. BASEMODEL

import { Index, PrimaryGeneratedColumn } from "typeorm";

export class BaseModel {
    @PrimaryGeneratedColumn('uuid')
    id: string
}

审计模型

import { Exclude } from "class-transformer";
import { RequestContext } from "src/utils/req-ctx";
import { BeforeInsert, BeforeUpdate, Column, CreateDateColumn, DeleteDateColumn, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";

export class AuditModel {

    @Column({ name: "created_by", default: null })
    created_by: string

    @Column({ name: "modified_by", default: null })
    modified_by: string

    @BeforeInsert()
    setAuditsBeforeInsert() {
        console.log(RequestContext.currentRequest)
        if (RequestContext.currentRequest.currentUser) {
            this.created_by = this.modified_by = RequestContext.currentRequest.currentUser.name
        }
    }

    @BeforeUpdate()
    setAuditsBeforeUpdate() {
        if (RequestContext.currentRequest.currentUser) {
            this.modified_by = RequestContext.currentRequest.currentUser.name
        }
    }
}

用户模型

import { BaseModel } from 'src/base-models/base-model';
import { AuditModel } from 'src/base-models/audit-model';

function mixin(...classes: any[]): any {
  class MixedClass {}

  classes.forEach((clazz) => {
    Object.getOwnPropertyNames(clazz.prototype).forEach((name) => {
      MixedClass.prototype[name] = clazz.prototype[name];
    });
  });

  return MixedClass;
}

@Entity()
@Unique(['email'])
export class Users extends mixin(BaseModel,AuditModel) {
//Other user attributes
}

我正在尝试这种方法,我希望它以同样的方式,因为有一些其他的模型,扩展了一些其他的模式与基本模型。
有人能帮我让它工作吗?

e5nszbig

e5nszbig1#

您可以轻松地扩展实体,并且baseClass的列将由childClass继承,如下所示:

export class MultiTenantEntity
    {
      @ManyToOne(() => Tenant, { onDelete: 'CASCADE' })
      @JoinColumn({ name: 'tenant_id' })
      tenant: Tenant;
      @Column({ name: 'tenant_id', type: 'uuid' })
      tenantId: string;
    }

@Entity()
export class Product extends MultiTenantEntity {
  @Column({ length: 255 })
  name: string;

  @Column({ length: 255, nullable: true })
  description: string;
}

相关问题