forked from Sfippa/api-client-v1-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.js
42 lines (36 loc) · 1015 Bytes
/
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
var request = require('request-promise')
var q = require('q')
var 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)
var 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)
var 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
function parseResponse (response) {
try { return JSON.parse(response) } catch (e) { return response }
}
function handleError (e) {
throw e.error || e || 'Unexpected error'
}