Hi I don't wanted to keep adding common columns to all entity. So I'm thinking to write it on separate class and extend it to those which needs those columns. I Tried something but it is throwing " Classes can only extend a single class" Error
I don't have much hands on on TS, I'm new to TS. Can anyone help me out ?
Please find the below code:
1.Base Entity
import { Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity()
export class BaseModel {
@PrimaryGeneratedColumn("uuid")
id: string;
}
import { CreateDateColumn, DeleteDateColumn, Entity, UpdateDateColumn } from "typeorm";
@Entity()
export class AuditModel {
@CreateDateColumn()
created!: Date;
@UpdateDateColumn()
updated!: Date;
@DeleteDateColumn()
deletedAt?: Date;
}
3.User Entity
import { AuditModel } from 'src/baseModels/auditEntity';
import { BaseModel } from 'src/baseModels/baseEntity';
import {
Entity,
Column
} from 'typeorm';
@Entity()
export class Users extends BaseModel,AuditModel {
@Column({ unique: true })
email: string;
@Column({ nullable: false })
name: string;
@Column({default:false})
isActive:boolean
@Column({ select: false })
password: string;
}
Unlike other languages, JavaScript does not allow you to extend more than one class (single inheritance).
I would suggest making your AuditModel extend BaseModel:
export class AuditModel extends BaseModel {
@CreateDateColumn()
created!: Date;
@UpdateDateColumn()
updated!: Date;
@DeleteDateColumn()
deletedAt?: Date;
}
Then your UsersModel only has to extend the AuditModel:
@Entity()
export class Users extends AuditModel {
@Column({ unique: true })
email: string;
@Column({ nullable: false })
name: string;
@Column({default:false})
isActive:boolean
@Column({ select: false })
password: string;
}
Do not use @Entity on classes that won't live in your database!