Skip to content

Instantly share code, notes, and snippets.

@teyfix
Created April 14, 2021 17:08
Show Gist options
  • Select an option

  • Save teyfix/cf0921a51c711ada6c5e02c9fc23f305 to your computer and use it in GitHub Desktop.

Select an option

Save teyfix/cf0921a51c711ada6c5e02c9fc23f305 to your computer and use it in GitHub Desktop.
useful typeorm base entities

Useful base entities for TypeORM

Attribute

Any database entity. Attributes are usually being used as a child for an Existence or a Reflection.

Existence

Entities that can be changed or deleted in time.

Reflection

Entities that has an equivalent in the real world. Not only these entities reflect a real life being like an object, or a person also abstract things like posts or comments.

import { BaseEntity, PrimaryGeneratedColumn, SaveOptions } from "typeorm";
export abstract class Attribute extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
save(options?: SaveOptions): Promise<this> {
return super.save(options);
}
}
import {
AfterInsert,
AfterLoad,
AfterUpdate,
Column,
CreateDateColumn,
DeleteDateColumn,
UpdateDateColumn
} from "typeorm";
import { Attribute } from "../attribute/attribute";
const DELETED_AT = Symbol("Existence.deletedAt");
export abstract class Existence extends Attribute {
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
@DeleteDateColumn()
deletedAt?: Date;
// to support duplicate unique entities
// when the old one is deleted
// @Index(['username', 'deletedAtMS'], { unique: true })
@Column()
deletedAtMS = 0;
@AfterLoad()
async onRead(): Promise<void> {
this[DELETED_AT] = this.deletedAt;
}
@AfterUpdate()
@AfterInsert()
async onWrite(): Promise<void> {
if (this.deletedAt !== this[DELETED_AT]) {
this.deletedAtMS = Date.now();
await this.save();
}
}
}
import { Column } from "typeorm";
import { Existence } from "../existence/existence";
export abstract class Reflection extends Existence {
@Column()
displayName: string;
@Column()
description?: string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment