UNPKG

2.17 kBJavaScriptView Raw
1/**
2 * Invocation context.
3 * @memberof module:apeman-commons-invocating/lib
4 * @inner
5 * @constructor InvocationPerformer
6 * @param {object} config - Performing configuration.
7 * @param {object} config.context - Invocation context.
8 */
9
10var async = require('async'),
11 InvocationLoader = require('./invocation_loader'),
12 InvocationContext = require('./invocation_context');
13
14/** @lends InvocationPerformer */
15function InvocationPerformer() {
16 var s = this;
17 s.init.apply(s, arguments);
18}
19
20InvocationPerformer.prototype = {
21 /** @constructs InvocationPerformer */
22 init: function (config) {
23 var s = this;
24 config = config || {};
25 s.context = new InvocationContext(config.context || {});
26 },
27 /**
28 * Execute an invocation.
29 * @param {object} invocation
30 * @param {function} callback - Callback when done.
31 */
32 perform: function (invocation, callback) {
33 var s = this;
34 var loader = new InvocationLoader({});
35 async.waterfall([
36 function (callback) {
37 loader.load(invocation.$invoke, callback);
38 },
39 function ($invoke, callback) {
40 var $args = s._getAmbiguously(invocation, '$args|$arg|$argument|$arguments|args|arg|argument|arguments') || [],
41 $options = s._getAmbiguously(invocation, '$options|$option|$opt|$opts|options|option|opt|opts') || {};
42 var context = s.context.clone().set({
43 $args: $args,
44 $options: $options
45 });
46 var args = [context].concat($args || []).concat($options || {}).concat(callback);
47 $invoke.apply(context, args);
48 }
49 ], callback);
50 },
51 _getAmbiguously: function (data, ambiguousKey) {
52 var keys = ambiguousKey.split(/\|/g);
53 for (var i = 0, len = keys.length; i < len; i++) {
54 var key = keys[i];
55 var hit = data.hasOwnProperty(key) || (!!data[key]) || (data[key] === 0);
56 if (hit) {
57 return data[key];
58 }
59 }
60 return null;
61 }
62};
63
64module.exports = InvocationPerformer;