|
|
@ -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(); |
|
|
|
} |
|
|
|
} |
|
|
|