Browse Source

agent: refactor to re-start connections

master
Guillermo Rauch 9 years ago
parent
commit
704727a863
  1. 19
      lib/agent.js

19
lib/agent.js

@ -13,21 +13,31 @@ import fetch from 'node-fetch';
*/ */
export default class Agent { export default class Agent {
constructor (host) { constructor (host, { debug }) {
this._host = host; this._host = host;
this._agent = http2.createAgent({ this._debug = debug;
host, this._initAgent();
}
_initAgent () {
return http2.createAgent({
host: this._host,
port: 443 port: 443
}).once('error', (err) => this._onError(err)); }).once('error', (err) => this._onError(err));
} }
_onError (err) { _onError (err) {
// XXX: should we `this.emit()`? // XXX: should we `this.emit()`?
if (this._debug) console.log('> [debug] connection error', err.stack);
this._error = err; this._error = err;
} }
fetch (path, opts = {}) { fetch (path, opts = {}) {
if (this._error) throw new Error('HTTP2 connection error'); if (this._error) {
if (this._debug) console.log('> [debug] re-initializing agent after error');
this._error = null;
this._initAgent();
}
const { body } = opts; const { body } = opts;
opts.agent = this._agent; opts.agent = this._agent;
@ -45,6 +55,7 @@ export default class Agent {
} }
close () { close () {
if (this._debug) console.log('> [debug] closing agent');
return this._agent.close(); return this._agent.close();
} }
} }

Loading…
Cancel
Save