forked from toniopelo/loopback-cascade-delete-mixin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cascade-delete.js
86 lines (70 loc) · 3.09 KB
/
cascade-delete.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
'use strict';
var debug = require('debug')('loopback:mixins:cascade-delete');
var _ = require('lodash');
module.exports = function (Model, options) {
Model.observe('after delete', function (ctx, next) {
var name = idName(Model);
var hasInstanceId = ctx.instance && ctx.instance[name];
var hasWhereId = (ctx.where && ctx.where[name]) || (ctx.where && ctx.where.and && ctx.where.and[0].id);
var hasMixinOption = options && _.isArray(options.relations);
if (!(hasWhereId || hasInstanceId)) {
debug('Skipping delete for ', Model.definition.name);
return next();
}
if (!hasMixinOption) {
debug('Skipping delete for', Model.definition.name, 'Please add mixin options');
return next();
}
var modelInstanceId = getIdValue(Model, ctx.instance || ctx.where);
var deletedRelations = _.map(cascadeDeletes(), function (deleteRelation) {
return deleteRelation(modelInstanceId);
});
Promise.all(deletedRelations)
.then(function () {
debug('Cascade delete has successfully finished');
next();
})
.catch(function (err) {
debug('Error with cascading deletes', err);
next(err);
});
});
function cascadeDeletes() {
return _.map(options.relations, function (relation) {
return function (modelId) {
debug('Relation ' + relation + ' model ' + Model.definition.name);
if (!Model.relations[relation]) {
debug('Relation ' + relation + ' not found for model ' + Model.definition.name);
throw 'Relation ' + relation + ' not found for model ' + Model.definition.name;
}
var relationModel = Model.relations[relation].modelTo;
var relationKey = Model.relations[relation].keyTo;
if (Model.relations[relation].modelThrough) {
relationModel = Model.relations[relation].modelThrough;
}
var where = {};
where[relationKey] = modelId;
if (options.deepDelete) {
let relationModelIdName = relationModel.getIdName();
let fields = {};
fields[relationModelIdName] = true;
return relationModel.find({where: where, fields: fields}).then(function (instancesToDelete) {
let deleteOperations = [];
for (let instance of instancesToDelete) {
deleteOperations.push(relationModel.deleteById(instance[relationModelIdName]));
}
return Promise.all(deleteOperations);
});
} else {
return relationModel.destroyAll(where);
}
};
});
}
function idName(m) {
return m.definition.idName() || 'id';
}
function getIdValue(m, data) {
return data && (data[idName(m)] || data.and[0][idName(m)]);
}
};