forked from Sfippa/api-client-v1-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.js
46 lines (39 loc) · 1.08 KB
/
api.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
'use strict';
var request = require('request-promise')
, q = require('q')
, urljoin = require('url-join');
function API(rootUrl, endpoints) {
this.rootUrl = rootUrl;
this.endpoints = endpoints;
}
API.prototype.request = function (api, options) {
try {
var endpoint = this.endpoints[api].stringify(options)
, apiurl = urljoin(this.rootUrl, endpoint);
return request(apiurl).then(parseResponse).catch(handleError);
} catch (err) {
return q.reject(err);
}
};
API.prototype.post = function (api, options, body) {
try {
var endpoint = this.endpoints[api].stringify(options)
, apiurl = urljoin(this.rootUrl, endpoint);
return request({
method: 'POST',
url : apiurl,
form : body
}).then(parseResponse).catch(handleError);
} catch (err) {
return q.reject(err);
}
};
module.exports = API;
// Helper functions
function parseResponse(response) {
try { return JSON.parse(response); }
catch (e) { return response; }
}
function handleError(e) {
throw e.error || e || 'Unexpected error';
}