forked from postalserver/postal-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Client.js
49 lines (41 loc) · 1.13 KB
/
Client.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
var Promise = require('promise');
var https = require('https');
var concatStream = require('concat-stream');
function Client(host, serverKey) {
this.host = host;
this.serverKey = serverKey;
}
Client.prototype.makeRequest = function makeRequest(controller, action, parameters) {
return new Promise(function (resolve, reject) {
var data = JSON.stringify(parameters);
var request = https.request({
headers: {
'Content-Type': 'application/json',
'X-Server-API-Key': this.serverKey
},
host: this.host,
method: 'POST',
path: '/api/v1/' + controller + '/' + action
}, function (response) {
response.pipe(concatStream(function (content) {
var json
try {
json = JSON.parse(content);
} catch (error) {
return reject(error);
}
if (json.status === 'success') {
resolve(json.data);
} else {
reject(json.data);
}
}));
});
request.on('error', function (error) {
reject(error);
});
request.write(data);
request.end();
}.bind(this));
};
module.exports = Client;