forked from curtislacy/chain-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp-utility.js
More file actions
85 lines (71 loc) · 1.84 KB
/
http-utility.js
File metadata and controls
85 lines (71 loc) · 1.84 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
77
78
79
80
81
82
83
84
85
var request = require('request');
var fs = require('fs');
var path = require('path');
var util = require('util');
var URL = 'https://api.chain.com';
var PEM = fs.readFileSync(path.join(__dirname, './chain.pem'));
module.exports = HttpUtility;
function HttpUtility(c) {
if(c.auth == null) {
c.auth = "GUEST-TOKEN";
};
this.auth = c.auth;
if (c.url == null) {
c.url = URL;
};
this.url = c.url;
this.PEM = PEM;
}
HttpUtility.prototype.makeRequest = function(method, path, body, options, cb) {
var usingJson = false;
var r = {
strictSSL: true,
cert: this.PEM,
auth: this.auth,
method: method,
uri: this.url + path
};
if(body != null) {
usingJson = true;
r['json'] = body;
}
if(options != null) {
r['qs'] = options;
}
request(r, function(err, resp, body) {
if (err) {
return cb(err);
}
if (Math.floor(resp.statusCode / 100) != 2) {
err = new Error("Chain SDK error: bad status code " + resp.statusCode.toString() + ". See 'resp' property for more detail.");
err.resp = resp;
return cb(err);
}
if(usingJson) {
return cb(err, body);
}
var parsed;
try {
parsed = JSON.parse(body);
} catch (e) {
err = new Error("Chain SDK error: could not decode JSON response. See 'error' and 'resp' properties for more detail.");
err.error = e;
err.resp = resp;
return cb(err);
}
cb(null, parsed);
});
};
HttpUtility.prototype.post = function(path, body, cb) {
this.makeRequest('POST', path, body, null, cb);
};
HttpUtility.prototype.delete = function(path, cb) {
this.makeRequest('DELETE', path, null, null, cb);
};
HttpUtility.prototype.get = function(path, options, cb) {
if (typeof(options) == 'function') {
cb = options;
options = null;
}
this.makeRequest('GET', path, null, options, cb);
}