/
pipeline.js
83 lines (67 loc) · 2.12 KB
/
pipeline.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
/** @license MIT License (c) copyright 2010-2013 original author or authors */
/**
* Licensed under the MIT License at:
* http://www.opensource.org/licenses/mit-license.php
*
* @author: Brian Cavalier
* @author: John Hann
*/
(function(define) { 'use strict';
define(function(require) {
var when, compose, pipelineSplitRx;
when = require('when');
compose = require('./functional').compose;
pipelineSplitRx = /\s*\|\s*/;
return function pipeline(proxy, composeString, wire) {
var bindSpecs, resolveRef, getProxy;
if(typeof composeString != 'string') {
return wire(composeString).then(function(func) {
return createProxyInvoker(proxy, func);
});
}
bindSpecs = composeString.split(pipelineSplitRx);
resolveRef = wire.resolveRef;
getProxy = wire.getProxy;
function createProxyInvoker(proxy, method) {
return function() {
return proxy.invoke(method, arguments);
};
}
function createBound(proxy, bindSpec) {
var target, method;
target = bindSpec.split('.');
if(target.length > 2) {
throw new Error('Only 1 "." is allowed in refs: ' + bindSpec);
}
if(target.length > 1) {
method = target[1];
target = target[0];
return when(getProxy(target), function(proxy) {
return createProxyInvoker(proxy, method);
});
} else {
if(proxy && typeof proxy.get(bindSpec) == 'function') {
return createProxyInvoker(proxy, bindSpec);
} else {
return resolveRef(bindSpec);
}
}
}
// First, resolve each transform function, stuffing it into an array
// The result of this reduce will an array of concrete functions
// Then add the final context[method] to the array of funcs and
// return the composition.
return when.reduce(bindSpecs, function(funcs, bindSpec) {
return when(createBound(proxy, bindSpec), function(func) {
funcs.push(func);
return funcs;
});
}, []).then(
function(funcs) {
var context = proxy && proxy.target;
return (funcs.length == 1 ? funcs[0] : compose(funcs)).bind(context);
}
);
};
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));