-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
134 lines (113 loc) · 2.48 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
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
'use strict';
/**
* Module dependencies.
*/
var assert = require('assert');
var debug = require('debug')('ware');
var Emitter = require('events').EventEmitter;
var compose = require('koa-compose');
var co = require('co');
var slice = Array.prototype.slice;
/**
* Ware prototype.
*/
var w = Ware.prototype;
/**
* Expose Ware.
*/
exports = module.exports = Ware;
/**
* Initialize a new `Ware` manager.
*
* @api public
*/
function Ware() {
if (!(this instanceof Ware)) return new Ware;
this.on('error', this.onerror);
this.middleware = [];
this.context = Object.create(null);
}
/**
* Inherit from `Emitter.prototype`.
*/
Ware.prototype.__proto__ = Emitter.prototype;
/**
* Use the given middleware `fn`.
*
* @param {GeneratorFunction} fn
* @return {Ware} self
* @api public
*/
w.use = function (fn) {
assert(fn && 'GeneratorFunction' == fn.constructor.name,
'ware.use() requires a generator function');
debug('use %s', fn._name || fn.name || '-');
this.middleware.push(fn);
return this;
};
/**
* Run through the middleware with the given `args`
* and optional `callback`.
*
* @param {Mixed} args...
* @param {GeneratorFunction} callback (optional)
* @return {Mixed}
* @api public
*/
w.run = function () {
debug('run');
var mw = [].concat(this.middleware);
var args = slice.call(arguments);
var last = args[args.length - 1];
var callback = 'function' === typeof last ? last : null;
if (callback) {
args.pop();
mw.push(callback);
}
var gen = compose(mw);
var fn = co.wrap(gen);
var ctx = this.createContext(args, Object.create(null), this);
return fn.call(ctx).catch(ctx.onerror);
};
/**
* Clear the midleware.
*
* @return {Object} self
* @api public
*/
w.clear = function () {
this.middleware.length = 0;
return this;
};
/**
* Create a context.
*
* @param {Mixed} input
* @return {Object} ctx
* @api private
*/
w.createContext = function (input, output, self) {
var ctx = Object.create(self.context);
ctx.input = input;
ctx.output = output;
ctx.onerror = function (err) {
if (!err) return;
self.removeListener('error', self.onerror);
self.emit('error', err);
};
return ctx;
};
/**
* Default error handler.
*
* @param {Error} err
* @api private
*/
w.onerror = function (err){
assert(err instanceof Error, 'non-error thrown: ' + err);
if (this.listeners('error').length) return;
var msg = err.stack || err.toString();
console.error();
console.error(msg.replace(/^/gm, ' '));
console.error();
};