-
Notifications
You must be signed in to change notification settings - Fork 0
/
koa-inject.js
82 lines (68 loc) · 1.26 KB
/
koa-inject.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
'use strict';
var Injector = require('simple-injector');
module.exports = exports = Inject;
/**
*
* @param app {Application}
* @param (modules) {{}}
* @returns {Injector}
*/
Inject.init = function (app, modules) {
app.di = new Injector();
app.context.di = app.di;
if (modules) preLoad(app.di, modules);
return app.di;
};
/**
*
* @param di {Injector}
* @param modules {{}}
*/
function preLoad(di, modules) {
Object.keys(modules).forEach(loadModule);
function loadModule(name) {
di.set(name, modules[name]);
}
}
/**
*
*/
function Inject(gen) {
var deps;
var matches = gen.toString().match(/^function *\*[a-zA-Z0-9_\$ ]*\(([^\)]*)/);
if (!matches) {
throw new Error('Invalid generator function passed');
}
if (!matches[1]) {
return noop(gen);
}
deps = matches[1].split(/, */);
/**
*
*/
return function *(next) {
var args = deps.map(mapFn, this);
return yield gen.apply(this, args)
/**
*
* @param dep
* @returns {*}
*/
function mapFn(dep) {
if (dep === 'next') {
return next;
}
return this.di.get(dep);
}
};
}
/**
*
* @param gen
* @returns {Function}
*/
function noop(gen) {
return function * () {
return gen.apply(this, arguments);
};
}