UNPKG

2.8 kBJavaScriptView Raw
1(function() {
2 var Batman, querystring, url;
3 var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
4 url = require('url');
5 querystring = require('querystring');
6 Batman = require('./batman').Batman;
7 Batman.Request.prototype.getModule = function(protocol) {
8 var requestModule;
9 return requestModule = (function() {
10 switch (protocol) {
11 case 'http:':
12 case 'https:':
13 return require(protocol.slice(0, -1));
14 default:
15 throw "Unrecognized request protocol " + protocol;
16 }
17 })();
18 };
19 Batman.Request.prototype.send = function(data) {
20 var auth, options, path, protocol, request, requestModule, requestURL, _ref;
21 this.fire('loading');
22 requestURL = url.parse(this.get('url', true));
23 protocol = requestURL.protocol;
24 requestModule = this.getModule(protocol);
25 path = requestURL.pathname;
26 if (this.get('method') === 'GET') {
27 path += querystring.stringify(Batman.mixin({}, requestURL.query, this.get('data')));
28 }
29 options = {
30 path: path,
31 method: this.get('method'),
32 port: requestURL.port,
33 host: requestURL.hostname,
34 headers: {}
35 };
36 auth = this.get('username') ? "" + (this.get('username')) + ":" + (this.get('password')) : requestURL.auth ? requestURL.auth : void 0;
37 if (auth) {
38 options.headers["Authorization"] = "Basic " + (new Buffer(auth).toString('base64'));
39 }
40 if ((_ref = options.method) === "PUT" || _ref === "POST") {
41 options.headers["Content-type"] = this.get('contentType');
42 }
43 request = requestModule.request(options, __bind(function(response) {
44 data = [];
45 response.on('data', function(d) {
46 return data.push(d);
47 });
48 return response.on('end', __bind(function() {
49 var status;
50 data = data.join();
51 this.set('response', data);
52 status = this.set('status', response.statusCode);
53 if ((status >= 200 && status < 300) || status === 304) {
54 this.fire('success', data);
55 } else {
56 request.request = this;
57 this.fire('error', request);
58 }
59 return this.fire('loaded');
60 }, this));
61 }, this));
62 auth = this.get('username') ? "" + (this.get('username')) + ":" + (this.get('password')) : requestURL.auth ? requestURL.auth : void 0;
63 if (auth) {
64 request.setHeader("Authorization", new Buffer(auth).toString('base64'));
65 }
66 if (this.get('method' === 'POST')) {
67 request.write(JSON.stringify(this.get('data')));
68 }
69 request.end();
70 request.on('error', function(e) {
71 this.set('response', error);
72 this.fire('error', error);
73 return this.fire('loaded');
74 });
75 return request;
76 };
77 exports.Batman = Batman;
78}).call(this);