UNPKG

1.67 kBJavaScriptView Raw
1'use strict';
2
3var EventEmitter = require('events').EventEmitter;
4var util = require('util');
5var utility = require('utility');
6var urllib = require('./urllib');
7
8module.exports = HttpClient;
9
10function 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}
31util.inherits(HttpClient, EventEmitter);
32
33HttpClient.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
48HttpClient.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
59function getAgent(agent, defaultAgent) {
60 return agent === undefined ? defaultAgent : agent;
61}