forked from Meteor-Community-Packages/meteor-method-hooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.js
53 lines (40 loc) · 1.25 KB
/
common.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
import { Meteor } from 'meteor/meteor';
const hasOwn = Object.prototype.hasOwnProperty;
const methodHooks = Object.create(null);
const allMethodHooks = { before: [], after: [] };
function registerMethodHook(methodNames, position, fn) {
if (!Array.isArray(methodNames)) {
// eslint-disable-next-line
methodNames = [methodNames];
}
const results = [];
for (const methodName of methodNames) {
if (!methodHooks[methodName]) {
methodHooks[methodName] = {
before: [],
after: [],
};
}
results.push(methodHooks[methodName][position].unshift(fn));
}
return results;
}
Meteor.beforeMethod = (methodName, fn) => registerMethodHook(methodName,
'before', fn);
Meteor.afterMethod = (methodName, fn) => registerMethodHook(methodName,
'after', fn);
Meteor.beforeAllMethods = fn => allMethodHooks.before.unshift(fn);
Meteor.afterAllMethods = fn => allMethodHooks.after.unshift(fn);
function getHooks(method, point) {
const fns = [...allMethodHooks[point]];
if (hasOwn.call(methodHooks, method)) {
fns.push(...methodHooks[method][point]);
}
return fns;
}
export function getHooksBefore(method) {
return getHooks(method, 'before');
}
export function getHooksAfter(method) {
return getHooks(method, 'after');
}