API with NestJS #129. Implementing soft deletes with SQL and Kysely

NestJS SQL

This entry is part 129 of 136 in the API with NestJS

When working on our REST APIs, we usually focus on implementing the four fundamental operations: creating, reading, updating, and deleting (CRUD). Deleting entities is a common feature in many web applications. The simplest way to do it is by permanently deleting rows from the database. In this article, we use Kysely to explore the idea of soft deletes that enable us to keep deleted entities within the database.

The purpose of soft deletes

The simplest way to add the soft delete feature is through a boolean flag.

In the above code, we use the DEFAULT keyword. This means that the flag is set to false by default whenever we insert an entity into our database.

We don’t use the keyword when we want to do a soft delete on the record above. Instead, we don’t delete it permanently. To achieve that, we change the value in the column.

The important thing is that implementing soft deletes impacts various queries. For instance, we need to consider it when retrieving the list of all entities.

Soft delete pros

The most apparent benefit of soft deletes is that we can quickly recover the deleted entities. While backups can also do this, soft deletes provide a better user experience. A practical example is an undo button that sets the ¬†flag back to false. We can also retrieve the deleted records from the database, even though we’ve marked them as removed. This can be helpful when we want to create a report that includes all our records, for instance.

Soft deletes can also come in handy when handling relationships. For instance, permanently deleting a record referenced in another table can lead to a foreign constraint violation. This doesn’t occur with soft deletes because we don’t remove the entities from the database.

If you want to learn more about constraints, check out API with NestJS #124. Handling SQL constraints with Kysely

Soft delete cons

A significant drawback of soft deletes is that we have to account for them in all associated queries. If we retrieve our data and overlook filtering by the column, we could provide the data the users shouldn’t have access to. Implementing this filtering can also impact our performance.

Another important thing to consider is the unique constraint. Let’s examine the table we defined in one of the earlier parts of this series.

20230813165809_add_users_table.ts

In the situation mentioned above, we require a unique email for each user. With hard deletes, deleting users would free up their email for others to use. However, with soft deletes, we don’t remove records from the database, so deleting users this way doesn’t make their emails available to others.

Implementing soft deletes with Kysely

A commonly used approach for soft deletes involves storing the deletion date instead of a simple boolean flag.

20231015202921_add_comments_table.ts

If you’re interested in learning more about dates in PostgreSQL, take a look at Managing date and time with PostgreSQL and TypeORM

Besides creating the migration, we also need to design an appropriate interface.

commentsTable.ts

We also need to add it to our interface.

database.ts

Besides the above, we must create a model to handle the data returned from the database.

comment.model.ts

Creating records

To create an entity, we first need to define a Data Transfer Object that validates the data coming from the user.

comment.dto.ts

Please notice that we are not allowing the users to set the value of the column. Instead, we want it to be null by default.

comments.repository.ts

Above, we look for the foreign key violations to detect if the user tried to create a comment for an article that does not exist.

Deleting records

A critical aspect of soft deletes is managing the DELETE method correctly.

comments.controller.ts

The query in our repository should correctly set the value for the column. One approach to achieve this is using the function built into PostgreSQL, which provides the current date and time and the timezone.

comments.repository.ts

We use to disallow removing an entity already marked as deleted.

Fetching records

Considering the column in the rest of our queries is essential. A good example is when fetching records. For starters, we need to filter out the records with the values using .

comments.repository.ts

Thanks to the above, attempting to retrieve a record marked as deleted will result in the 404 Not Found error.

Updating records

The use of soft deletes can also impact how we implement updating entities. We aim for our API to return a 404 Not Found error when a user attempts to update a record marked as deleted.

comments.repository.ts

Restoring records

There might be instances where we want to restore a deleted entity. Thankfully, this simple task can be accomplished by setting the value in the column to null.

Summary

In this article, we’ve explored soft deletes and discussed their advantages and disadvantages. Soft deletes can enhance the user experience when deleting and restoring entities. However, they do introduce added complexity to all of our SQL queries. Despite this, soft deletes have specific use cases and can be valuable in certain situations.

Series Navigation<< API with NestJS #128. Managing JSON data with PostgreSQL and KyselyAPI with NestJS #130. Avoiding storing sensitive information in API logs >>
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments