source: Dev/trunk/src/server/util/request.js @ 529

Last change on this file since 529 was 529, checked in by hendrikvanantwerpen, 11 years ago
  • Added grey icons for better highlighting, synced block and large buttons.
  • Introduced extra color for text, now disabled/inactive/hovered -> it's not very clear though.
  • Added confirmation on irrevertable actions.
  • Added support for query string in our new request implementation.
File size: 2.0 KB
Line 
1var HTTPResult = require('./http-result')
2  , HTTP = require('http')
3  , HTTPS = require('https')
4  , URL = require('url')
5  , QS = require('querystring')
6  , _ = require('underscore')
7  ;
8
9module.exports = function(url, options) {
10
11    var result = new HTTPResult();
12   
13    var body = options.body;
14    delete options.body;
15
16    var json = options.json;
17    delete options.json;
18
19    var reqOpts = _.isString(url) ? URL.parse(url) : url;
20    _.extend(reqOpts,options);
21    if ( json === true ) {
22        options.headers = options.headers || {};
23        _.extend(options.headers,{
24            'Content-Type': 'application/json',
25            'Accepts': 'application/json'
26        });
27    }
28    if ( reqOpts.qs ) {
29        reqOpts.path = (reqOpts.path||'')+'?'+QS.stringify(reqOpts.qs);
30        delete reqOpts.qs;
31    }
32
33    var protocol = reqOpts.protocol;
34    var httpModule;
35    if ( protocol === 'http:' ) {
36        httpModule = HTTP;
37    } else if ( protocol === 'https:' ) {
38        httpModule = HTTPS;
39    } else {
40        throw new Error("Unknown protocol "+protocol);
41    }
42
43    var req = httpModule.request(reqOpts);
44    req.on('response', function(response) {
45        var data = "";
46        response.setEncoding('utf8');
47        response.on('data', function(chunk) {
48            data += chunk;
49        });
50        response.on('end', function() {
51            var body;
52            try {
53                if ( json ) {
54                    if ( data ) { body = JSON.parse(data); }
55                } else {
56                    body = data;
57                }
58                result.set(response.statusCode,body);
59            } catch (ex) {
60                console.log('error',data);
61                result.set(-1,ex);
62            }
63        });
64        response.on('error', function(error) {
65            result.set(-1,error);
66        });
67    });
68    req.on('error', function(error){
69        result.set(-1,error);
70    });
71
72    if ( body ) {
73        req.write(json ? JSON.stringify(body) : body);
74    }
75    req.end();
76
77    return result;
78   
79};
Note: See TracBrowser for help on using the repository browser.