objection-soft-delete
A plugin that adds soft-delete functionality to Objection.js
Installation
NPM
npm i objection-soft-delete --save
Yarn
yarn add objection-soft-delete
Usage
Mixin the plugin on an object representing a table that uses a boolean column as a flag for soft delete
// Import objection model.const Model = Model; // Import the pluginconst softDelete = ; // Mixin the plugin and specify the column to to use. 'deleted' will be used if none is specified: columnName: 'deleted' Model static { return 'Users'; } static { return type: 'object' required: properties: id: type: 'integer' // matches the columnName passed above deleted: type: 'boolean' // other columns }
deleted
field of your table has a default value of false
(and, while not required, you'll probably want to make it not nullable as well). A deleted
value of NULL
will result in this plugin producing unexpected behavior.
Note: Make sure the .delete()
or .del()
is called for that model, the matching row(s) are flagged true
instead of deleted
When Delete a User:
await User; // db now has: { User id: 1, deleted: true, ... }
Or:
const user = await User;await user; // same
Deleted rows are still in the db:
const deletedUser = await User; // => { User id: 1, deleted: true, ... }
Filter out deleted rows without having to remember each model's "deleted" columnName:
const activeUsers = await User;
Get only deleted rows:
const deletedUsers = await User;
Restore row(s):
await User; // db now has: { User id: 1, deleted: false, ... }
Permanently remove row(s) from the db:
await Userquery; // => row with id:1 is permanently deleted
.eager()
or .joinRelation()
Filtering out deleted/undeleted records in Using the named filters
A notDeleted
and a deleted
filter will be added to the list of named filters for any model that mixes in the plugin. These filters use the .whereNotDeleted()
and .whereDeleted()
functions to filter records, and can be used without needing to remember the specific columnName for any model:
// some other Model with a relation to the `User` model:const group = await UserGroup ; // => now group.users contains only records that are not deleted
Or:
// some other Model with a relation to the `User` model:const group = await UserGroup ; // => now group.users contains only records that are deleted
With .joinRelation()
:
// some other Model with a relation to the `User` model:const group = await UserGroup ; // => all groups that have an undeleted user whose first name starts with 'a';
Using a relationship filter
A filter can be applied directly to the relationship definition to ensure that deleted/undeleted rows never appear:
// some other class that has a FK to User: static { return 'UserGroups'; } ... static { return users: relation: ModelManyToManyRelation modelClass: User join: from: 'UserGroups.id' through: from: 'GroupUsers.groupId' to: 'GroupUsers.userId' to: 'Users.id' { f; // or f.whereDeleted(), as needed. } }
then:
const group = await UserGroup ; // => `User` rows are filtered out automatically without having to specify the filter here
columnName
Per-model If for some reason you have to deal with different column names for different models (legacy code/schemas can be a bear!), all functionality is fully supported:
columnName: 'deleted' Model ... columnName: 'inactive' Model ... // everything will work as expected:await User ; // => all undeleted users await UserGroup ; // => all undeleted user groups await UserGroup ; // => all undeleted user groups, with all related undeleted users eagerly loaded await User ; // => all deleted users, with all related deleted user groups eagerly loaded await User ; // => all undeleted users that belong to undeleted user groups that have a name containing the string 'local', eagerly load all undeleted groups for said users. // and so on...
.upsertGraph()
Using with This plugin was actually born out of a need to have .upsertGraph()
soft delete in some tables, and hard delete in others, so it plays nice with
.upsertGraph()
:
// a model with soft deleteModel static { return 'Phones'; } // a model without soft delete static { return 'Emails'; } // assume a User model that relates to both, and the following existing data:User id: 1 name: 'Johnny Cash' phones: id: 6 number: '+19195551234' emails: id: 3 address: 'mib@americanrecords.com' // then: await User; // => phone id 6 will be flagged deleted (and will still be related to Johnny!), email id 3 will be removed from the database
Lifecycle Functions
One issue that comes with doing soft deletes is that your calls to .delete()
will actually trigger lifecycle functions for .update()
, which may not be expected or desired. To help address this, some context flags have been added to the queryContext
that is passed into lifecycle functions to help discern whether the event that triggered (e.g.) $beforeUpdate
was a true update, a soft delete, or an undelete:
if queryContextsoftDelete // do something before a soft delete, possibly including calling your $beforeDelete function. // Think this through carefully if you are using additional plugins, as their lifecycle // functions may execute before this one depending on how you have set up your inheritance chain! else if queryContextundelete // do something before an undelete else // do something before a normal update // same procedure for $afterUpdate
Available flags are:
- softDelete
- undelete
Flags will be true
if set, and undefined
otherwise.
Checking Whether a Model is SoftDelete
All models with the soft delete mixin will have an isSoftDelete
property, which returns true
.
Options
columnName: the name of the column to use as the soft delete flag on the model (Default: 'deleted'
). The column must exist on the table for the model.
You can specify different column names per-model by using the options:
const softDelete = columnName: 'inactive';
deletedValue: you can set this option to allow a different value than "true" to be set in the specified column. For instance, you can use the following code to make a timestamp (you need knex instance to do so)
const softDelete = columnName: 'deleted_at' deletedValue: knexfn;
notDeletedValue: you can set (and should) this option along with deletedValue
to allow a different value than "false" to be set in the specified column.
For instance, you can use the following code to restore the column to null (you need knex instance to do so)
const softDelete = columnName: 'deleted_at' deletedValue: knexfn notDeletedValue: null;
Tests
Tests can be run with:
npm test
or:
yarn test
Linting
The linter can be run with:
npm run lint
or:
yarn lint
Contributing
The usual spiel: fork, fix/improve, write tests, submit PR. I try to maintain a (mostly) consistent syntax, but am open to suggestions for improvement. Otherwise, the only two rules are: do good work, and no tests = no merge.