knorm-soft-delete v2.1.2
knorm-soft-delete
Soft-delete plugin for knorm.
Installation
npm install --save knorm knorm-soft-deleteknorm-soft-delete has a peer dependency on knorm
Usage
const knorm = require('knorm');
const knormSoftDelete = require('knorm-soft-delete');
const orm = knorm({
// knorm options
}).use(knormSoftDelete({
// knormSoftDelete options
}));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:
namestring, default: deleted: the field name to use instead ofdeletedcolumnstring, 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:
namestring, default: deletedAt: the field name to use instead ofdeletedAtcolumnstring, 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 Model.query.onlyDeleted().update({ foo: 'bar' });
// or:
await Model.query.where({ deleted: true }).update({ foo: 'bar' });
// to fetch rows including soft-deleted rows:
await Model.query.withDeleted().where({ foo: 'bar' }).fetch();
// or:
await Model.query.where({ foo: 'bar', deleted: [ true, false ] }).fetch();NOTE:
withDeletedperforms better thanwhere({ deleted: [true, false] })
where({ deleted: [true, false] })translates toWHERE deleted IN (true, false)The field name used in the
wheremethod 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 new Model({ id: 1 }).delete();
// to restore:
await new Model({ id: 1 }).restore();
// or:
await Model.restore({ where: { id: 1 } });
// or to hard-delete:
await new Model({ id: 1 }).hardDelete();
// or:
await Model.hardDelete({ where: { id: 1 } });