In the src/common/database/base-model.ts
file, you need to import DeleteDateColumn
and add the following field:
...
@DeleteDateColumn()
typublic deletedAt?: Date;
...
You must have something like this:
import {
CreateDateColumn,
DeleteDateColumn,
Generated,
PrimaryColumn,
UpdateDateColumn,
} from 'typeorm';
export class BaseModel {
@PrimaryColumn({ type: 'uuid' })
@Generated('uuid')
public id?: string;
@CreateDateColumn()
public createdAt?: Date;
@UpdateDateColumn()
public updatedAt?: Date;
@DeleteDateColumn()
public deletedAt?: Date;
}
Now, you need to use the softDelete
method on each of your repositories.
public async softDelete(id: number): Promise<void> {
await this.myEntityRepository.softDelete(id);
}
If you want to restore a record, you can use the restore method like shown below.
public async restore(id: number): Promise<void> {
await this.myEntityRepository.restore(id);
}
If you need to include deleted records in a search, you must include the field withDeleted: true
in the query you are performing.
For example:
await this.myEntityRepository.find({ withDeleted: true })
await this.myEntityRepository.findOne(
id,
{
relations: ['myEntityTwo'],
withDeleted: true
}
);
If you need to permanently delete a record, you can use the repository's delete method.
Migration
Now in the migrations you create, you must add a deleted_at
field of type Timestamp
to record the date the record was deleted.
Example:
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "public"."user" ("id" uuid NOT NULL uuid_generate_v4(), "email" character varying NOT NULL, "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), "deleted_at" TIMESTAMP , CONSTRAINT "PK_a7bc321b7d03b91d2ab32258321" PRIMARY KEY ("id"))`
);
}
If you already have tables created in your database, you must do an alter table to add a new column deleted_at
.
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "public"."user" ADD COLUMN deleted_at TIMESTAMP`
);
}