-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
73 lines (56 loc) · 1.34 KB
/
index.js
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
var qs = require('querystring');
var https = require('https');
var API_HOST = 'api.collection.cooperhewitt.org';
var API_PATH = '/rest/';
var API_PORT = 443;
module.exports = {
call: function(method, args, oncomplete) {
if (! oncomplete){
oncomplete = function(rsp){
console.log(rsp);
};
}
args['method'] = method;
var body = qs.stringify(args);
var headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': body.length,
};
var opts = {
rejectUnauthorized: false,
host: API_HOST,
port: API_PORT,
path: API_PATH,
method: 'POST',
headers: headers
};
var req = https.request(opts, function(res){
var status = res.statusCode;
if ((status < 200) || (status > 299)){
rsp = {'stat': 'error', 'error': { 'message': 'API call failed with status code ' + status } };
oncomplete(rsp);
return;
}
res.setEncoding('utf8');
var rsp = '';
res.on('data', function(chunk){
rsp += chunk;
});
res.on('end', function(){
try {
rsp = JSON.parse(rsp);
oncomplete(rsp);
}
catch(e){
rsp = {'stat': 'error', 'error': { 'message': 'Failed to parse JSON, ' + e } };
oncomplete(rsp);
}
});
res.on('error', function(e){
console.log(e);
});
});
req.write(body);
req.end();
}
};