Reputation: 457
let say there are different entity User, Role, Task
All these entities have createdBy
, updatedBy
, createdOn
, updatedOn
in common.
I want to know how can I create a base entity such that all entity extends base class in nest js using Typeform.
Upvotes: 4
Views: 6500
Reputation: 1813
This is the place where should you use inheritance.
Basically, the idea is to have a base class/entity that gathers common logic or structure where many other classes/entities share that common logic.
For example: Cat, Dog, Elephant are all having similar characterizations, so we might want to gather all these similar characterizations at a single place in order to avoid duplication of logic and code.
So let's see the simplest example only for basic understanding.
export class Animal {
protected numberOfLegs: number;
protected sound(): void;
}
export class Dog extends Animal {
constructor() {
super();
this.numberOfLegs = 4;
}
sound(): void {
console.log('BARK');
}
}
For your needs:
Export a base entity.
import { Entity, Column } from 'typeorm';
export class BaseEntity {
@Column()
createdBy: string;
@Column()
updatedBy: string;
@Column()
createdOn: Date;
@Column()
updatedOn: Date;
}
And then inherit it from derived entities.
import { Entity, Column } from 'typeorm';
import {BaseEntity} from './base-entity';
export class DerivedEntity extends BaseEntity {
@Column()
id: string;
...
}
Please read about inheritance which is a basic and very important principle in programming and OOP.
Upvotes: 4