From 704727a863f2638bddc959c5d2067ac6b94b8459 Mon Sep 17 00:00:00 2001 From: Guillermo Rauch Date: Fri, 26 Feb 2016 14:41:42 -0800 Subject: [PATCH] agent: refactor to re-start connections --- lib/agent.js | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/lib/agent.js b/lib/agent.js index bd1ce4b..1ec090d 100644 --- a/lib/agent.js +++ b/lib/agent.js @@ -13,21 +13,31 @@ import fetch from 'node-fetch'; */ export default class Agent { - constructor (host) { + constructor (host, { debug }) { this._host = host; - this._agent = http2.createAgent({ - host, + this._debug = debug; + this._initAgent(); + } + + _initAgent () { + return http2.createAgent({ + host: this._host, port: 443 }).once('error', (err) => this._onError(err)); } _onError (err) { // XXX: should we `this.emit()`? + if (this._debug) console.log('> [debug] connection error', err.stack); this._error = err; } 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; opts.agent = this._agent; @@ -45,6 +55,7 @@ export default class Agent { } close () { + if (this._debug) console.log('> [debug] closing agent'); return this._agent.close(); } }