-
-
Notifications
You must be signed in to change notification settings - Fork 92
/
remove.js
92 lines (83 loc) · 2.11 KB
/
remove.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
87
88
89
90
91
92
import { EJSON } from 'meteor/ejson'
import { CollectionHooks } from './collection-hooks'
const isEmpty = (a) => !Array.isArray(a) || !a.length
CollectionHooks.defineWrapper(
'remove',
async function (
userId,
_super,
instance,
hooks,
getTransform,
args,
suppressHooks
) {
const ctx = { context: this, _super, args }
const [selector, callback] = args
const async = typeof callback === 'function'
let docs
let abort
const prev = []
if (!suppressHooks) {
try {
if (!isEmpty(hooks.before) || !isEmpty(hooks.after)) {
const cursor = await CollectionHooks.getDocs.call(
this,
instance,
selector
)
docs = await cursor.fetch()
}
// copy originals for convenience for the 'after' pointcut
if (!isEmpty(hooks.after)) {
docs.forEach((doc) => prev.push(EJSON.clone(doc)))
}
// before
for (const o of hooks.before) {
for (const doc of docs) {
const r = await o.hook.call(
{ transform: getTransform(doc), ...ctx },
userId,
doc
)
if (r === false) {
abort = true
break
}
}
if (abort) {
break
}
}
if (abort) return 0
} catch (e) {
if (async) return callback.call(this, e)
throw e
}
}
async function after (err) {
if (!suppressHooks) {
for (const o of hooks.after) {
for (const doc of prev) {
await o.hook.call(
{ transform: getTransform(doc), err, ...ctx },
userId,
doc
)
}
}
}
}
if (async) {
const wrappedCallback = async function (err, ...args) {
await after(err)
return callback.call(this, err, ...args)
}
return _super.call(this, selector, wrappedCallback)
} else {
const result = await _super.call(this, selector, callback)
await after()
return result
}
}
)