-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathindex.js
More file actions
178 lines (157 loc) · 5.01 KB
/
index.js
File metadata and controls
178 lines (157 loc) · 5.01 KB
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
'use strict';
const co = require('co');
const util = require('util');
const is = require('is-type-of');
const assert = require('assert');
const awaitEvent = require('await-event');
const awaitFirst = require('await-first');
const EventEmitter = require('events').EventEmitter;
class Base extends EventEmitter {
constructor(options) {
super();
if (options && options.initMethod) {
assert(is.function(this[options.initMethod]),
`[sdk-base] this.${options.initMethod} should be a function.`);
process.nextTick(() => {
if (is.generatorFunction(this[options.initMethod])) {
this[options.initMethod] = co.wrap(this[options.initMethod]);
}
const ret = this[options.initMethod]();
assert(is.promise(ret), `[sdk-base] this.${options.initMethod} should return either a promise or a generator`);
ret.then(() => this.ready(true))
.catch(err => this.ready(err));
});
}
this.options = options || {};
this._ready = false;
this._readyError = null;
this._readyCallbacks = [];
// support `yield this.await('event')`
this.await = awaitEvent;
this.awaitFirst = awaitFirst;
this.on('error', err => { this._defaultErrorHandler(err); });
}
_wrapListener(eventName, listener) {
if (is.generatorFunction(listener) || is.asyncFunction(listener)) {
assert(eventName !== 'error', '[sdk-base] `error` event should not have a generator/async listener.');
const newListener = (...args) => {
let promise;
if (is.asyncFunction(listener)) {
promise = listener(...args);
} else {
promise = co(function* () {
yield listener(...args);
});
}
promise.catch(err => {
err.name = 'EventListenerProcessError';
this.emit('error', err);
});
};
newListener.original = listener;
return newListener;
}
return listener;
}
addListener(eventName, listener) {
return super.addListener(eventName, this._wrapListener(eventName, listener));
}
on(eventName, listener) {
return super.on(eventName, this._wrapListener(eventName, listener));
}
once(eventName, listener) {
return super.once(eventName, this._wrapListener(eventName, listener));
}
prependListener(eventName, listener) {
return super.prependListener(eventName, this._wrapListener(eventName, listener));
}
prependOnceListener(eventName, listener) {
return super.prependOnceListener(eventName, this._wrapListener(eventName, listener));
}
removeListener(eventName, listener) {
let target = listener;
if (is.generatorFunction(listener) || is.asyncFunction(listener)) {
const listeners = this.listeners(eventName);
for (const fn of listeners) {
if (fn.original === listener) {
target = fn;
break;
}
}
}
return super.removeListener(eventName, target);
}
/**
* detect sdk start ready or not
* @return {Boolean} ready status
*/
get isReady() {
return this._ready;
}
/**
* set ready state or onready callback
*
* @param {Boolean|Error|Function} flagOrFunction - ready state or callback function
* @return {void|Promise} ready promise
*/
ready(flagOrFunction) {
if (arguments.length === 0) {
// return a promise
// support `this.ready().then(onready);` and `yield this.ready()`;
return new Promise((resolve, reject) => {
if (this._ready) {
return resolve();
} else if (this._readyError) {
return reject(this._readyError);
}
this._readyCallbacks.push(err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
} else if (is.function(flagOrFunction)) {
this._readyCallbacks.push(flagOrFunction);
} else if (flagOrFunction instanceof Error) {
this._ready = false;
this._readyError = flagOrFunction;
if (!this._readyCallbacks.length) {
this.emit('error', flagOrFunction);
}
} else {
this._ready = flagOrFunction;
}
if (this._ready || this._readyError) {
this._readyCallbacks.splice(0, Infinity).forEach(callback => {
process.nextTick(() => {
callback(this._readyError);
});
});
}
}
_defaultErrorHandler(err) {
if (this.listeners('error').length > 1) {
// ignore defaultErrorHandler
return;
}
console.error('\n[%s][pid: %s][%s] %s: %s \nError Stack:\n %s',
Date(), process.pid, this.constructor.name, err.name,
err.message, err.stack);
// try to show addition property on the error object
// e.g.: `err.data = {url: '/foo'};`
const additions = [];
for (const key in err) {
if (key === 'name' || key === 'message') {
continue;
}
additions.push(util.format(' %s: %j', key, err[key]));
}
if (additions.length) {
console.error('Error Additions:\n%s', additions.join('\n'));
}
console.error();
}
}
module.exports = Base;