-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpClientFactory.js
More file actions
78 lines (63 loc) · 2.11 KB
/
httpClientFactory.js
File metadata and controls
78 lines (63 loc) · 2.11 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
const request = require("request");
/**
HTTP (POST requests) Client for ViciAuth, sends requests with viciauth app key and api key in header
@param uri{string} - API paths of ViciAuth.com
@param params{Object} - Body of the request
@param callback{function}, called with (err,ViciAuthUser)
*/
const httpClientFactory = (API_KEY, APP_KEY, OPTS) => (uri, params, callback) => {
console.log("[INFO] [ViciAuth] Calling uri %s",uri);
params = params || {};
if (!callback) {
throw "[ERROR] call method must be provided with callback function!"
}
if (!APP_KEY) {
console.log("[WARNING] [ViciAuth] No app key");
}
if (!API_KEY) {
console.log("[WARNING] [ViciAuth] No api key");
}
var requestOptions = {
headers : OPTS.headers || {}
};
requestOptions.url = OPTS.protocol + "://" + OPTS.host + ":" + OPTS.port + uri;
requestOptions.headers['x-auth-viciauth-app-key'] = APP_KEY;
requestOptions.headers['x-auth-viciauth-api-key'] = API_KEY;
requestOptions.headers['x-auth-viciauth-token'] = params.token
const method = OPTS.method.toLowerCase();
if (method !== 'get') {
requestOptions.form = params; //{ token : params.token };
}
request[method](requestOptions, (err, response, body) => {
if (err) {
try {
err = JSON.parse(err);
} catch(e) {
console.error(err);
}
return callback({
status:502,
err:err
});
}
if (body) {
try {
body = JSON.parse(body);
} catch(err) {
console.error("[ERROR] ViciAuthSDK : Something went wrong");
console.error(err);
return callback({ err: body });
}
} else {
body = {};
}
if (response.statusCode !== 200) {
return callback({
status: response.statusCode,
err: body
});
}
return callback(null, body);
});
};
module.exports = httpClientFactory;