0

I'm working on a nest Project , where I have to extend my entity class to have common columns from other class. BASEMODEL

import { Index, PrimaryGeneratedColumn } from "typeorm";

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

AUDITMODEL

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

USERMODEL

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
}

I'm trying this approach, I wanted it in the same way, there are because there are some other models which extend some other mode with base model.

Can anyone please help me to make it work?

1 Answers1

0

You can easily extend the entity and the columns of the baseClass will be inherited by the childClass as the following ex:

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;
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31