1 | 'use strict';
|
2 |
|
3 | var EventEmitter = require('events').EventEmitter;
|
4 | var util = require('util');
|
5 | var utility = require('utility');
|
6 | var urllib = require('./urllib');
|
7 |
|
8 | module.exports = HttpClient;
|
9 |
|
10 | function HttpClient(options) {
|
11 | EventEmitter.call(this);
|
12 | options = options || {};
|
13 |
|
14 | if (options.agent !== undefined) {
|
15 | this.agent = options.agent;
|
16 | this.hasCustomAgent = true;
|
17 | } else {
|
18 | this.agent = urllib.agent;
|
19 | this.hasCustomAgent = false;
|
20 | }
|
21 |
|
22 | if (options.httpsAgent !== undefined) {
|
23 | this.httpsAgent = options.httpsAgent;
|
24 | this.hasCustomHttpsAgent = true;
|
25 | } else {
|
26 | this.httpsAgent = urllib.httpsAgent;
|
27 | this.hasCustomHttpsAgent = false;
|
28 | }
|
29 | this.defaultArgs = options.defaultArgs;
|
30 | }
|
31 | util.inherits(HttpClient, EventEmitter);
|
32 |
|
33 | HttpClient.prototype.request = HttpClient.prototype.curl = function (url, args, callback) {
|
34 | if (typeof args === 'function') {
|
35 | callback = args;
|
36 | args = null;
|
37 | }
|
38 | args = args || {};
|
39 | if (this.defaultArgs) {
|
40 | args = utility.assign({}, [ this.defaultArgs, args ]);
|
41 | }
|
42 | args.emitter = this;
|
43 | args.agent = getAgent(args.agent, this.agent);
|
44 | args.httpsAgent = getAgent(args.httpsAgent, this.httpsAgent);
|
45 | return urllib.request(url, args, callback);
|
46 | };
|
47 |
|
48 | HttpClient.prototype.requestThunk = function (url, args) {
|
49 | args = args || {};
|
50 | if (this.defaultArgs) {
|
51 | args = utility.assign({}, [ this.defaultArgs, args ]);
|
52 | }
|
53 | args.emitter = this;
|
54 | args.agent = getAgent(args.agent, this.agent);
|
55 | args.httpsAgent = getAgent(args.httpsAgent, this.httpsAgent);
|
56 | return urllib.requestThunk(url, args);
|
57 | };
|
58 |
|
59 | function getAgent(agent, defaultAgent) {
|
60 | return agent === undefined ? defaultAgent : agent;
|
61 | }
|