forked from Meteor-Community-Packages/meteor-method-hooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
46 lines (36 loc) · 1.09 KB
/
server.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
import { Meteor } from 'meteor/meteor';
import { getHooksAfter, getHooksBefore } from './common';
function wrap(methodName) {
const fn = Meteor.server.method_handlers[methodName];
return function wrappedMethodHandler(...args) {
this._methodName = methodName;
const beforeFns = getHooksBefore(methodName);
const afterFns = getHooksAfter(methodName);
if (!beforeFns.length && !afterFns.length) {
return fn.apply(this, args);
}
for (const beforeFn of beforeFns) {
if (Promise.await(beforeFn.apply(this, args)) === false) {
return false;
}
}
try {
this.result = Promise.await(fn.apply(this, args));
} catch (error) {
this.error = error;
}
for (const afterFn of afterFns) {
try { Promise.await(afterFn.apply(this, args)); } catch (error) { /* */ }
}
if (this.error) {
throw this.error;
}
return this.result;
};
}
Meteor.startup(() => {
const methodHandlers = Meteor.server.method_handlers;
Object.keys(methodHandlers).forEach((method) => {
methodHandlers[method] = wrap(method);
});
});