TypeORM Soft Delete and Flag Usage
TypeORM Soft Delete and Flag Usage
Introduction: What is Soft Delete and Why Is It Used?
In database operations, the "Delete" operation is usually performed in a way that cannot be undone. However, in some applications, instead of deleting the record completely, only its visibility is closed and the data needs to be kept in the background. This method is called soft delete. TypeORM is a powerful ORM tool that makes this process practical in modern applications. Thanks to TypeORM soft delete, you can manage delete operations safely and flexibly without losing your data.
Using TypeORM Soft Delete
TypeORM supports the soft delete process either by using @DeleteDateColumn or with a flag approach (e.g., isDeleted). The most common method is to define @DeleteDateColumn and mark the relevant field in the entity. Thus, when a record is deleted, it is not actually removed from the database, only a timestamp is added to the deletedAt column:
import { Entity, PrimaryGeneratedColumn, Column, DeleteDateColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@DeleteDateColumn({ nullable: true })
deletedAt?: Date;
}
Now, it is easy to "delete" records via soft delete using the TypeORM repository or manager:
await userRepository.softDelete(id);
In this operation, the deletedAt field is updated and the record does not appear in normal queries. If desired, all data including deleted records can be listed using the withDeleted() function:
const users = await userRepository.find({ withDeleted: true });
Control Deletion with Flag: Using isDeleted
In some projects, it may be necessary to use a boolean flag such as isDeleted. In these scenarios, the relevant field is added to the entity and the soft delete operation is performed manually:
@Entity()
export class Product {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column({ default: false })
isDeleted: boolean;
}
// Soft delete operation
await productRepository.update(id, { isDeleted: true });
In this method, you must always check isDeleted: false in queries. In addition, to ensure data security, this structure is usually considered at the application level.
Conclusion: Comparison of TypeORM Soft Delete and Flag Approaches
TypeORM Soft Delete and Flag usage provides full control and flexibility when deleting data in your application. With @DeleteDateColumn, management is automated and integration in queries becomes easier, while with the isDeleted flag, more customizable and complex deletion rules can be applied. By choosing the most appropriate method for your project requirements, you can prevent data loss and make management easier. The TypeORM soft delete function is a vital tool that enhances data quality and security in modern REST API and enterprise software projects.

Yorum Gönder