-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.js
255 lines (223 loc) · 7.12 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
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/* eslint-disable func-names */
/**
* Class to handle json api calls
* @type {*}
*/
const { v4: uuidv4 } = require('uuid')
const { fetchWrapper } = require('./fetchUtils')
module.exports = (function () {
const MIME_JSON = 'application/json'
const MIME_TEXT = 'text/plain'
const HEADER_ACCEPT = 'accept'
const REQUEST_GUID = 'request-guid'
// helper functions
/*
* normalize headers, i.e. lower case all header names.
*/
function normalizeHeaders(headers) {
if (!headers || typeof headers !== 'object') return {}
const normalizedHeaders = {}
for (const name in headers) {
if (Object.prototype.hasOwnProperty.call(headers, name)) {
normalizedHeaders[name.toLowerCase()] = headers[name]
}
}
return normalizedHeaders
}
/**
*
*/
function defaultOptions(requestOptions) {
const options = { ...requestOptions } || {}
// default options
options.port = requestOptions.port
options.method = requestOptions.method || 'GET'
options.path = requestOptions.path || '/'
options.headers = requestOptions.headers || {}
options.json = requestOptions.json || true
options.qsOptions = requestOptions.qsOptions || { arrayFormat: 'brackets' }
if (requestOptions.encoding || requestOptions.encoding === null) {
options.encoding = requestOptions.encoding
} else {
options.encoding = 'utf8'
}
if (typeof requestOptions.https === 'undefined' || requestOptions.https) {
options.https = true
} else {
options.https = false
}
options.headers = normalizeHeaders(options.headers)
return options
}
/*
* build the call uri
*/
function buildRequestUri(options) {
let requestUri = 'http://'
if (options.https) {
requestUri = 'https://'
}
requestUri += options.host
if (options.port) {
requestUri += ':' + options.port
}
requestUri += options.path
return requestUri
}
/*
* response handler wrapper function
*/
function handleResponse(self, onSuccess, onError) {
return function (error, response, body) {
const errFunc = onError || function () {}
const succFunc = onSuccess || function () {}
if (error) {
errFunc(error)
self.debugPrint('Error: ' + error)
} else {
// if status code is bad, return an error
if (response.statusCode >= 400) {
errFunc({
statusCode: response.statusCode,
body: response.body,
})
}
succFunc(body)
self.debugPrint('Response: ' + response.statusCode, body)
}
}
}
/**
* Constructor for the Api class
* @param options the options object:
* {
* port : int / default: 443
* method : string / default: GET
* host : string / default: none / MANDATORY
* path : string / default: '/'
* debugMode : boolean / default: false
* https : boolean / default: true
* headers : object / default: undefined
* json : boolean / default: false
* encoding : string / default: 'utf8'
* }
* @constructor
*/
function Api(apiOptions) {
// default options
const options = defaultOptions(apiOptions)
this.debugMode = apiOptions.debugMode || false
this.httpRequestSettings = {
url: buildRequestUri(options),
qs: options.query || {},
qsStringifyOptions: options.qsOptions,
method: options.method,
json: options.json,
body: JSON.stringify(options.data),
headers: options.headers,
encoding: options.encoding,
}
this.debugPrint = function (msg) {
const self = this
if (self.debugMode) {
// eslint-disable-next-line no-console
console.log(msg)
}
}
}
/**
* Wrap our constructor in a factory method.
* @param options our options object
* @returns {Api} a new instance of an Api class
*/
function factory(options) {
return new Api(options)
}
/**
* Sends a GET request to the configured api expecting a JSON response
*
* @param onSuccess callback for success, receives the response json data as a parameter
* @param onError callback for then call fails, receives the error as a parameter
*/
Api.prototype.getJson = function (onSuccess, onError) {
const self = this
self.httpRequestSettings.headers[HEADER_ACCEPT] = MIME_JSON
self.httpRequestSettings.headers[REQUEST_GUID] = uuidv4()
self.httpRequestSettings.method = 'GET'
delete self.httpRequestSettings.body
self.request(onSuccess, onError)
}
/**
* Sends a GET request to the configured api expecting a text/plain response
*
* @param onSuccess callback for success, receives the response text data as a parameter
* @param onError callback for then call fails, receives the error as a parameter
*/
Api.prototype.getText = function (onSuccess, onError) {
const self = this
self.json = false
self.httpRequestSettings.headers[HEADER_ACCEPT] = MIME_TEXT
self.httpRequestSettings.headers[REQUEST_GUID] = uuidv4()
self.httpRequestSettings.method = 'GET'
delete self.httpRequestSettings.body
self.request(onSuccess, onError)
}
/**
* Sends a POST request to the configured api, with a JSON payload
*
* @param data the payload to send to the server
* @param onSuccess callback for success, receives the response json data as a parameter
* @param onError callback for then call fails, receives the error as a parameter
*/
Api.prototype.postJson = function (data, onSuccess, onError) {
const self = this
self.httpRequestSettings.json = true
self.httpRequestSettings.method = 'POST'
self.httpRequestSettings.body = data
self.httpRequestSettings.headers[REQUEST_GUID] = uuidv4()
self.request(onSuccess, onError)
}
/**
* Sends a request to the configured api
*
* @param onSuccess callback for success, receives the response json data as a parameter
* @param onError callback for then call fails, receives the error as a parameter
*/
Api.prototype.request = function (onSuccess, onError) {
const self = this
self.debugPrint('GET Request settings: ' + JSON.stringify(self.httpRequestSettings))
// handle response, i.e. call correct callback
fetchWrapper(self.httpRequestSettings, handleResponse(self, onSuccess, onError))
}
/**
* Sends a GET request to the configured api expecting a text/plain response
*/
Api.prototype.promisedGetText = function () {
return new Promise((resolve, reject) =>
this.getText(
data => resolve(data),
err => reject(err)
)
)
}
/**
* Method returning api calls as promise.
* The promise will be resolved with
* - the error if call fails
* - the response object/json
* @return promise for the api call
*/
Api.prototype.promisedApiCall = function () {
return new Promise((resolve, reject) => {
this.httpRequestSettings.headers[HEADER_ACCEPT] = '*/*'
this.httpRequestSettings.headers[REQUEST_GUID] = uuidv4()
this.httpRequestSettings.method = 'GET'
delete this.httpRequestSettings.body
return this.request(
data => resolve(data),
err => reject(err)
)
})
}
return factory
})()