forked from timhuff/objection-soft-delete
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
60 lines (53 loc) · 1.74 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
'use strict' // eslint-disable-line
module.exports = (incomingOptions) => {
const options = Object.assign({
columnName: 'deleted',
}, incomingOptions);
return (Model) => {
class SDQueryBuilder extends Model.QueryBuilder {
// override the normal delete function with one that patches the row's "deleted" column
delete() {
const patch = {};
patch[options.columnName] = true;
return this.patch(patch);
}
// provide a way to actually delete the row if necessary
hardDelete() {
return super.delete();
}
// provide a way to undo the delete
undelete() {
const patch = {};
patch[options.columnName] = false;
return this.patch(patch);
}
// provide a way to filter to ONLY deleted records without having to remember the column name
whereDeleted() {
// qualify the column name
return this.where(`${this.modelClass().tableName}.${options.columnName}`, true);
}
// provide a way to filter out deleted records without having to remember the column name
whereNotDeleted() {
// qualify the column name
return this.where(`${this.modelClass().tableName}.${options.columnName}`, false);
}
}
return class extends Model {
static get QueryBuilder() {
return SDQueryBuilder;
}
// add a named filter for use in the .eager() function
static get namedFilters() {
// patch the notDeleted filter into the list of namedFilters
return Object.assign({}, super.namedFilters, {
notDeleted: (b) => {
b.whereNotDeleted();
},
deleted: (b) => {
b.whereDeleted();
},
});
}
};
};
};