-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathindex.js
More file actions
74 lines (66 loc) · 2.3 KB
/
index.js
File metadata and controls
74 lines (66 loc) · 2.3 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
'use strict' // eslint-disable-line
module.exports = (incomingOptions) => {
const options = Object.assign({
columnName: 'deleted',
deletedValue: true,
notDeletedValue: false,
}, incomingOptions);
return (Model) => {
class SDQueryBuilder extends Model.QueryBuilder {
// override the normal delete function with one that patches the row's "deleted" column
delete() {
this.mergeContext({
softDelete: true,
});
const patch = {};
patch[options.columnName] = options.deletedValue;
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() {
this.mergeContext({
undelete: true,
});
const patch = {};
patch[options.columnName] = options.notDeletedValue;
return this.patch(patch);
}
// provide a way to filter to ONLY deleted records without having to remember the column name
whereDeleted() {
// this if is for backwards compatibility, to protect those that used a nullable `deleted` field
if (options.deletedValue === true) { return this.where(`${this.modelClass().tableName}.${options.columnName}`, options.deletedValue); }
// qualify the column name
return this.whereNot(`${this.modelClass().tableName}.${options.columnName}`, options.notDeletedValue);
}
// 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}`, options.notDeletedValue);
}
}
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();
},
});
}
static get isSoftDelete() {
return true;
}
};
};
};