@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
deleted
anddeletedAt
(if enabled) fields to theModel
class - modifies
Query.prototype.delete
method such that it does not actually delete a row but rather sets thedeleted
field totrue
anddeletedAt
to the current time (i.e.new Date()
) if the field is enabled. - modifies
Query.prototype.insert
) method to setdeleted
tofalse
before insert. - modifies
Query.prototype.fetch
,Query.prototype.update
) andQuery.prototype.delete
methods such that they always filter out soft-deleted rows (i.e. withdeleted
set totrue
).
info
- If
Query.prototype.insert
) is passed data wheredeleted
anddeletedAt
are already set, they are left as is. - If
Query.prototype.update
) is called withdeleted
set tofalse
, thendeletedAt
is set tonull
before the updated. Ifdeleted
istrue
, thendeletedAt
is 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: