knorm-soft-delete
Soft-delete plugin for knorm.
Installation
npm install --save knorm knorm-soft-delete
knorm-soft-delete has a peer dependency on knorm
Usage
const knorm = ;const knormSoftDelete = ; const orm = ;
Options
deleted
The deleted
field is always added, but the field and column names can be
configured. By default, the field has this config:
- field-name:
deleted
- column-name:
deleted
If passed as an object, supports these config options:
name
string, default: deleted: the field name to use instead ofdeleted
column
string, default: deleted: the column name to use instead ofdeleted
deletedAt
Can either be true
or an object for further configuration. If true
, it adds
a field to the Model
class with this config:
- field-name:
deletedAt
- column-name:
deleted_at
If passed as an object, supports these config options:
name
string, default: deletedAt: the field name to use instead ofdeletedAt
column
string, default: deleted_at: the column name to use instead ofdeleted_at
How it works
This plugin adds deleted
(by default) and deletedAt
(if configured) fields
to your models and also updates your query methods so that the delete
method
does not actually delete a row but rather sets the deleted
column to true
and deletedAt
to the current time (i.e. new Date()
) if the field is enabled.
For Query.prototype.insert
, deleted
will be set to false
.
It also modifies the behaviour of Query.prototype.fetch
,
Query.prototype.update
and Query.prototype.delete
so that they always filter
out soft-deleted rows. To work with soft-deleted rows, use
Query.prototype.withDeleted
, Query.prototype.onlyDeleted
or directly use the
Query.prototype.where
(or whereNot
, orWhere
, orWhereNot
) method:
// to update only soft-deleted rows:await Modelquery;// or:await Modelquery; // to fetch rows including soft-deleted rows:await Modelquery;// or:await Modelquery;
NOTE:
withDeleted
performs better thanwhere({ deleted: [true, false] })
where({ deleted: [true, false] })
translates toWHERE deleted IN (true, false)
The field name used in the
where
method depends on your configuration (but defaults todeleted
)
This plugin also adds Query.prototype.restore
, Model.prototype.restore
and
Model.restore
methods that can be used to restore soft-deleted records.
Conversely, it also adds Query.prototype.hardDelete
,
Model.prototype.hardDelete
and Model.hardDelete
that can be used to
hard-delete records:
// to delete:await id: 1 ;// to restore:await id: 1 ;// or:await Model; // or to hard-delete:await id: 1 ;// or:await Model;