@knorm/soft-delete
Knorm plugin that enables soft-deletion and automates working with deleted and
deleted_at table fields. This plugin adds soft-deletion fields to the
Model class and updates Query methods to enable soft-deletion.
Installation
@knorm/soft-delete has a peer dependency on @knorm/knorm
Usage
Options
| Option | Type | Default | Description |
|---|---|---|---|
| [name] | string | soft-delete | The name of the plugin, allows accessing the plugin instance via Knorm's plugin registry (Knorm.prototype.plugins) |
| [deleted] | object | Config options for the deleted field. | |
| [deleted.name] | string | deleted | The field-name for the deleted field. |
| [deleted.column] | string | deleted | The column-name for the deleted field. |
| [deletedAt] | object | Config options for the deletedAt field. | |
| [deletedAt.name] | string | deletedAt | The field-name for the deletedAt field. |
| [deletedAt.column] | string | deleted_at | The column-name for the deletedAt field. |
Features
Soft deletion
This plugin:
- adds
deletedanddeletedAt(if enabled) fields to theModelclass - modifies
Query.prototype.deletemethod such that it does not actually delete a row but rather sets thedeletedfield totrueanddeletedAtto the current time (i.e.new Date()) if the field is enabled. - modifies
Query.prototype.insert) method to setdeletedtofalsebefore insert. - modifies
Query.prototype.fetch,Query.prototype.update) andQuery.prototype.deletemethods such that they always filter out soft-deleted rows (i.e. withdeletedset totrue).
info
- If
Query.prototype.insert) is passed data wheredeletedanddeletedAtare already set, they are left as is. - If
Query.prototype.update) is called withdeletedset tofalse, thendeletedAtis set tonullbefore the updated. Ifdeletedistrue, thendeletedAtis set to the current time.
To work with soft-deleted rows, use the Query.prototype.withDeleted,
Query.prototype.onlyDeleted query options or directly use the
Query.prototype.where query option:
info
withDeleted performs better than Model.where.in({ deleted: [true, false] })
info
If directly using the where query option, the field-name to use for the
deleted field depends on the field's configuration.
Restoration
This plugin also adds Query.prototype.restore, Model.prototype.restore and
Model.restore methods that can be used to restore soft-deleted records:
Hard deletion
Conversely, it also adds Query.prototype.hardDelete,
Model.prototype.hardDelete and Model.hardDelete that can be used to
hard-delete records: