-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
58 lines (45 loc) · 1.38 KB
/
index.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
/*!
* use-ware <https://github.com/tunnckoCore/use-ware>
*
* Copyright (c) 2016 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
* Released under the MIT license.
*/
'use strict'
var utils = require('./utils')
module.exports = function useWare (app, opts) {
if (!utils.isObject(app) && typeof app !== 'function') {
throw new TypeError('useWare: expect `app` be an object or function')
}
opts = utils.isObject(opts) ? opts : {}
opts.prop = typeof opts.prop === 'string' ? opts.prop : 'plugins'
opts.prop = opts.prop.length > 0 ? opts.prop : 'plugins'
if (!utils.isArray(app[opts.prop])) {
utils.define(app, opts.prop, [])
}
utils.define(app, 'use', function use (fn, options) {
if (typeof fn !== 'function') {
throw new TypeError('app.use: expect `fn` be function')
}
var self = this || app
var params = utils.arrayify(opts.params)
params = params.length === 0 ? [self] : params
if (typeof opts.fn === 'function') {
opts.fn.call(self, self, options)
}
fn = fn.apply(self, params)
if (typeof fn === 'function') {
self[opts.prop].push(fn)
}
return self
})
utils.define(app, 'run', function run () {
var self = this || app
var len = self[opts.prop].length
var i = 0
while (i < len) {
self[opts.prop][i++].apply(self, arguments)
}
return self
})
return app
}