coreapi.js
1.62 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
'use strict';
const request = require('request');
const logger = require('komodo-sdk/logger');
const coreUrl = require('komodo-sdk/core-url');
logger.verbose(`CORE URL: ${coreUrl}`);
function doRequest(params, cb) {
return new Promise((resolve) => {
const options = {
url: `${coreUrl}/${params.path.replace(/^\/+/, '')}`,
method: params.method || 'GET',
qs: params.qs || null,
};
logger.verbose('Requesting to CORE', {
xid: params.xid, method: options.method, fullpath: options.url, qs: options.qs,
});
request(options, (err, res, body) => {
if (err) {
logger.warn(`COREAPI: Error doing HTTP ${options.method} to CORE. ${err.toString()}`, { xid: params.xid });
resolve(null);
if (typeof cb === 'function') cb(err);
return;
}
if (res.statusCode !== 200) {
logger.warn(`COREAPI: CORE returning HTTP STATUS CODE ${res.statusCode}, not 200`, { xid: params.xid, body });
resolve(null);
if (typeof cb === 'function') cb(err);
return;
}
let bodyObject;
try {
bodyObject = JSON.parse(body);
} catch (e) {
logger.verbose('COREAPI: CORE respond is not a JSON string');
resolve(body);
if (typeof cb === 'function') cb(err);
return;
}
resolve(bodyObject);
if (typeof cb === 'function') cb(err);
});
});
}
module.exports = doRequest;