forked from Xanir/NodeJS-RestSimplified
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRestSimplified.js
More file actions
76 lines (64 loc) · 1.63 KB
/
RestSimplified.js
File metadata and controls
76 lines (64 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
var Q = require('q');
var url = require('url');
var http = require('http');
var extend = require('util')._extend;
var RestfulService = function(connection, headers) {
if (typeof connection === 'string') {
connection = url.parse(connection);
}
if (!connection.headers) {
connection.headers = {};
}
extend(connection.headers, headers);
var doRequest = function(myConnection, data) {
var deferedHttp = Q.defer();
try {
if (data) {
if (typeof data === 'object') {
data = JSON.stringify(data);
}
myConnection.headers['Content-Length'] = data.length;
}
var req = http.request(myConnection, function(res) {
res.setEncoding('utf-8');
var responseString = '';
res.on('connect', function(data) {
responseString = "";
});
res.on('data', function(data) {
responseString += data;
});
res.on('end', function() {
deferedHttp.resolve(res.statusCode, responseString, res.headers);
});
});
if (data) {
req.write(data);
}
req.end();
} catch (e) {
console.log(e);
deferedHttp.reject(e);
}
return deferedHttp.promise;
};
this.get = function(path, headers) {
var myConnection = extend({}, connection);
myConnection.method = 'GET';
myConnection.path += path;
if (headers) {
extend(myConnection.headers, headers);
}
return doRequest(myConnection);
};
this.post = function(path, headers, data) {
var myConnection = extend({}, connection);
myConnection.method = 'POST';
myConnection.path += path;
if (headers) {
extend(myConnection.headers, headers);
}
return doRequest(myConnection, data);
};
};
exports.RestfulService = RestfulService;