-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathService.js
More file actions
239 lines (204 loc) · 7.92 KB
/
Service.js
File metadata and controls
239 lines (204 loc) · 7.92 KB
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
/**
* @author Labs64 <netlicensing@labs64.com>
* @license Apache-2.0
* @link https://netlicensing.io
* @copyright 2017 Labs64 NetLicensing
*/
import axios from 'axios';
import btoa from 'btoa';
import Constants from '../Constants';
import NlicError from '../errors/NlicError';
import pkg from '../../package.json';
let httpXHR = {};
let axiosInstance = null;
export default class Service {
static getAxiosInstance() {
return axiosInstance || axios;
}
static setAxiosInstance(instance) {
axiosInstance = instance;
}
static getLastHttpRequestInfo() {
return httpXHR;
}
/**
* Helper method for performing GET request to N
etLicensing API services. Finds and returns first suitable item with
* type resultType from the response.
*
* Context for the NetLicensing API call
* @param context
*
* the REST URL template
* @param urlTemplate
*
* The REST query parameters values. May be null if there are no parameters.
* @param queryParams
*
* @returns {Promise}
*/
static get(context, urlTemplate, queryParams) {
return Service.request(context, 'get', urlTemplate, queryParams);
}
/**
* Helper method for performing POST request to NetLicensing API services. Finds and returns first suitable item
* with type resultType from the response.
*
* context for the NetLicensing API call
* @param context
*
* the REST URL template
* @param urlTemplate
*
* The REST query parameters values. May be null if there are no parameters.
* @param queryParams
*
* @returns {Promise}
*/
static post(context, urlTemplate, queryParams) {
return Service.request(context, 'post', urlTemplate, queryParams);
}
/**
*
* @param context
* @param urlTemplate
* @param queryParams
* @returns {Promise}
*/
static delete(context, urlTemplate, queryParams) {
return Service.request(context, 'delete', urlTemplate, queryParams);
}
/**
* Send request to NetLicensing RestApi
* @param context
* @param method
* @param urlTemplate
* @param queryParams
* @returns {Promise}
*/
static request(context, method, urlTemplate, queryParams) {
const template = String(urlTemplate);
const params = queryParams || {};
if (!template) throw new TypeError('Url template must be specified');
// validate http method
if (['get', 'post', 'delete'].indexOf(method.toLowerCase()) < 0) {
throw new Error(`Invalid request type:${method}, allowed requests types: GET, POST, DELETE.`);
}
// validate context
if (!context.getBaseUrl(null)) {
throw new Error('Base url must be specified');
}
const request = {
url: encodeURI(`${context.getBaseUrl()}/${template}`),
method: method.toLowerCase(),
responseType: 'json',
headers: {
Accept: 'application/json',
'X-Requested-With': 'XMLHttpRequest',
},
transformRequest: [(data, headers) => {
if (headers['Content-Type'] === 'application/x-www-form-urlencoded') {
return Service.toQueryString(data);
}
if (!headers['NetLicensing-Origin']) {
// eslint-disable-next-line no-param-reassign
headers['NetLicensing-Origin'] = `NetLicensing/Javascript ${pkg.version}`;
}
return data;
}],
};
// only node.js has a process variable that is of [[Class]] process
if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
request.headers['User-agent'] = `NetLicensing/Javascript ${pkg.version}/node&${process.version}`;
}
if (['put', 'post', 'patch'].indexOf(request.method) >= 0) {
if (request.method === 'post') {
request.headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
request.data = params;
} else {
request.params = params;
}
switch (context.getSecurityMode()) {
// Basic Auth
case Constants.BASIC_AUTHENTICATION:
if (!context.getUsername()) throw new Error('Missing parameter "username"');
if (!context.getPassword()) throw new Error('Missing parameter "password"');
request.auth = {
username: context.getUsername(),
password: context.getPassword(),
};
break;
// ApiKey Auth
case Constants.APIKEY_IDENTIFICATION:
if (!context.getApiKey()) throw new Error('Missing parameter "apiKey"');
request.headers.Authorization = `Basic ${btoa(`apiKey:${context.getApiKey()}`)}`;
break;
// without authorization
case Constants.ANONYMOUS_IDENTIFICATION:
break;
default:
throw new Error('Unknown security mode');
}
return Service.getAxiosInstance()(request)
.then((response) => {
response.infos = Service.getInfo(response, []);
const errors = response.infos.filter(({ type }) => type === 'ERROR');
if (errors.length) {
const error = new Error(errors[0].value);
error.config = response.config;
error.request = response.request;
error.response = response;
throw error;
}
httpXHR = response;
return response;
})
.catch((e) => {
if (e.response) {
httpXHR = e.response;
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
const error = new NlicError(e);
error.config = e.config;
error.code = e.code;
error.request = e.request;
error.response = e.response;
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
const { data } = e.response;
if (data) {
error.infos = Service.getInfo(e.response, []);
const [info = {}] = error.infos.filter(({ type }) => type === 'ERROR');
error.message = info.value || 'Unknown';
}
throw error;
}
throw e;
});
}
static getInfo(response, def) {
try {
return response.data.infos.info || def;
} catch (e) {
return def;
}
}
static toQueryString(data, prefix) {
const query = [];
const has = Object.prototype.hasOwnProperty;
Object.keys(data)
.forEach((key) => {
if (has.call(data, key)) {
const k = prefix ? `${prefix}[${key}]` : key;
let v = data[key];
v = (v instanceof Date) ? v.toISOString() : v;
query.push((v !== null && typeof v === 'object')
? Service.toQueryString(v, k)
: `${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
}
});
return query.join('&')
.replace(/%5B[0-9]+%5D=/g, '=');
}
}