Feature: Soft Delete
Problem
I would like to know your opinion on implementing Soft Delete in TypeORM. I would love to help doing this.
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Implement Soft Delete in TypeORM
TypeORM does not natively support soft deletes, which means that when an entity is deleted, it is permanently removed from the database. This can lead to data loss and complicate data recovery processes. Soft delete functionality allows entities to be marked as deleted without actually removing them from the database, enabling easier data recovery and auditing.
Awaiting Verification
Be the first to verify this fix
- 1
Add Soft Delete Column
Modify your entity to include a 'deletedAt' column that will store the timestamp of when the entity was soft deleted. This column will be used to determine if the entity is considered deleted.
typescriptimport { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column({ nullable: true }) deletedAt: Date | null; } - 2
Create Soft Delete Method
Implement a method in your repository or service that sets the 'deletedAt' column to the current date when an entity is deleted. This method should be used instead of the standard delete method.
typescriptasync softDeleteUser(userId: number): Promise<void> { await this.userRepository.update(userId, { deletedAt: new Date() }); } - 3
Modify Query Logic
Adjust your queries to exclude entities that have a non-null 'deletedAt' value. This ensures that soft-deleted entities do not appear in your application logic.
typescriptconst users = await this.userRepository.find({ where: { deletedAt: null } }); - 4
Implement Restore Method
Create a method to restore soft-deleted entities by setting the 'deletedAt' column back to null. This allows users to recover deleted data.
typescriptasync restoreUser(userId: number): Promise<void> { await this.userRepository.update(userId, { deletedAt: null }); }
Validation
To confirm the fix worked, perform the following steps: 1) Soft delete an entity and check that the 'deletedAt' column is populated. 2) Query the entity and ensure it does not appear in the results. 3) Restore the entity and verify that the 'deletedAt' column is null and the entity is retrievable.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep