forked from rocknrolla777/loopback-cascade-delete-mixin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcascade-delete.js
73 lines (57 loc) · 2.35 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
'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];
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;
return relationModel.destroyAll(where);
}
});
}
function idName(m) {
return m.definition.idName() || 'id';
}
function getIdValue(m, data) {
return data && data[idName(m)];
}
};