@marxlnfcs/wildduck-api
Version:
Provides a client to interact with the wildduck api
211 lines (210 loc) • 11 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createHttpException = exports.createHttpProxySettings = exports.HttpClient = exports.createHttpClient = void 0;
const axios = require("axios");
const utilities_1 = require("./utilities");
const lodash_1 = require("lodash");
const invalid_proxy_exception_1 = require("../exceptions/invalid-proxy.exception");
const bad_request_exception_1 = require("../exceptions/bad-request.exception");
const not_found_exception_1 = require("../exceptions/not-found.exception");
const timeout_exception_1 = require("../exceptions/timeout.exception");
const unprocessable_entity_exception_1 = require("../exceptions/unprocessable-entity.exception");
const internal_server_error_exception_1 = require("../exceptions/internal-server-error.exception");
const unknown_error_exception_1 = require("../exceptions/unknown-error.exception");
const https = require("https");
const duration_calculator_1 = require("./duration-calculator");
function createHttpClient(options) {
return new HttpClient(options);
}
exports.createHttpClient = createHttpClient;
class HttpClient {
constructor(options) {
var _a, _b;
this.options = options;
this.http = axios.default.create({
headers: {
'X-Access-Token': ((_a = this.options) === null || _a === void 0 ? void 0 : _a.accessToken) || '',
},
timeout: (_b = this.options) === null || _b === void 0 ? void 0 : _b.timeout,
proxy: createHttpProxySettings(this.options)
});
}
createUrl(path, options) {
return this.buildRequestOptions('GET', path, options).url_full;
}
get(path, options) {
return this.request('GET', path, options);
}
post(path, options) {
return this.request('POST', path, options);
}
put(path, options) {
return this.request('PUT', path, options);
}
patch(path, options) {
return this.request('PATCH', path, options);
}
delete(path, options) {
return this.request('DELETE', path, options);
}
download(path, options) {
const request = this.buildRequestOptions((options === null || options === void 0 ? void 0 : options.method) || 'GET', path, options);
return this.http.request(Object.assign(Object.assign({}, request), { responseType: 'blob' }));
}
upload(path, options) {
const request = this.buildRequestOptions((options === null || options === void 0 ? void 0 : options.method) || 'GET', path, options);
return this.http.request(request);
}
request(method, path, options) {
return new Promise(async (resolve, reject) => {
var _a;
try {
const duration = (0, duration_calculator_1.createDurationCalculator)().start();
const request = this.buildRequestOptions(method, path, options);
this.onRequest(duration, request);
if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.delay) {
await Promise.resolve(new Promise((r) => setTimeout(() => r(), this.options.delay)));
}
this.http.request(request)
.then(response => {
duration.stop();
this.onResponse(duration, request, response);
resolve(response);
})
.catch((error) => {
duration.stop();
this.onError(duration, request, error);
reject(error);
});
}
catch (e) {
reject(e);
}
});
}
onRequest(duration, request) {
var _a, _b;
if ((0, lodash_1.isFunction)((_a = this.options) === null || _a === void 0 ? void 0 : _a.onRequest))
(_b = this.options) === null || _b === void 0 ? void 0 : _b.onRequest({
url: request.url_full,
request: request,
startDate: duration.startDate,
});
}
onResponse(duration, request, response) {
var _a, _b;
if ((0, lodash_1.isFunction)((_a = this.options) === null || _a === void 0 ? void 0 : _a.onResponse))
(_b = this.options) === null || _b === void 0 ? void 0 : _b.onResponse({
url: request.url_full,
request: request,
response: response,
startDate: duration.startDate,
endDate: duration.endDate,
duration: duration.duration,
durationString: duration.durationString
});
}
onError(duration, request, error) {
var _a, _b;
if ((0, lodash_1.isFunction)((_a = this.options) === null || _a === void 0 ? void 0 : _a.onError))
(_b = this.options) === null || _b === void 0 ? void 0 : _b.onError({
url: request.url_full,
request: request,
error: error,
startDate: duration.startDate,
endDate: duration.endDate,
duration: duration.duration,
durationString: duration.durationString
});
}
buildRequestOptions(method, path, options) {
options = Object.assign(Object.assign({}, (options || {})), { headers: (options === null || options === void 0 ? void 0 : options.headers) || null, params: (options === null || options === void 0 ? void 0 : options.params) || null, query: (options === null || options === void 0 ? void 0 : options.query) || null, body: (options === null || options === void 0 ? void 0 : options.body) || null });
const paths = (0, utilities_1.joinUrlPaths)(...(path ? Array.isArray(path) ? path : [path] : []));
let url = (0, utilities_1.isUrl)(paths) ? paths : (0, utilities_1.joinUrls)(this.options.baseUrl, ...[paths]);
let headers = {};
if (options === null || options === void 0 ? void 0 : options.headers) {
Object
.entries(options.headers)
.map(([headerName, headerValue]) => headers[headerName] = headerValue);
}
if (options.params) {
Object
.entries(options.params)
.filter(([key, value]) => !(0, lodash_1.isNil)(value))
.map(([key, value]) => url = url.replace(`:${key}`, `${value}`).replace(`{${key}}`, `${value}`));
}
if (options.query) {
const query = options.query;
options.query = {};
for (let [key, value] of Object.entries(query).filter(([key, value]) => !(0, lodash_1.isNil)(value))) {
options.query[key] = Array.isArray(value) ? value.join(',') : value;
if (!options.query[key]) {
delete options.query[key];
}
}
}
let url_full = !options.query ? url : `${url}?${Object.entries(options.query).map(e => `${e[0]}=${e[1]}`).join('?')}`;
return {
method: method,
url: url,
url_full: url_full,
headers: headers,
data: options === null || options === void 0 ? void 0 : options.body,
responseType: options === null || options === void 0 ? void 0 : options.responseType,
responseEncoding: options === null || options === void 0 ? void 0 : options.responseEncoding,
httpsAgent: new https.Agent({ rejectUnauthorized: this.options.rejectUnauthorized }),
params: ((options === null || options === void 0 ? void 0 : options.query) || {}),
};
}
}
exports.HttpClient = HttpClient;
function createHttpProxySettings(options) {
var _a, _b, _c, _d, _e, _f, _g;
if (typeof (options === null || options === void 0 ? void 0 : options.proxy) !== 'string' && !((_a = options === null || options === void 0 ? void 0 : options.proxy) === null || _a === void 0 ? void 0 : _a.url) && !((_b = options === null || options === void 0 ? void 0 : options.proxy) === null || _b === void 0 ? void 0 : _b.host)) {
return false;
}
if ((0, lodash_1.isString)(options.proxy) || ((_c = options === null || options === void 0 ? void 0 : options.proxy) === null || _c === void 0 ? void 0 : _c.url)) {
try {
const url = new URL((0, lodash_1.isString)(options.proxy) ? options.proxy : options.proxy.url);
return {
host: url.hostname,
port: parseInt(url.port),
protocol: url.protocol,
auth: !(0, lodash_1.isString)(options === null || options === void 0 ? void 0 : options.proxy) ? (_d = options === null || options === void 0 ? void 0 : options.proxy) === null || _d === void 0 ? void 0 : _d.auth : null
};
}
catch (e) {
throw (0, invalid_proxy_exception_1.createInvalidProxyUrlException)((0, lodash_1.isString)(options.proxy) ? options.proxy : options.proxy.url);
}
}
if (!((_e = options.proxy) === null || _e === void 0 ? void 0 : _e.host) || !((_f = options.proxy) === null || _f === void 0 ? void 0 : _f.port) || !((_g = options.proxy) === null || _g === void 0 ? void 0 : _g.protocol)) {
throw (0, invalid_proxy_exception_1.createInvalidProxyConfigException)(options);
}
return {
host: options.proxy.host,
port: options.proxy.port,
protocol: options.proxy.protocol.endsWith(':') ? options.proxy.protocol : options.proxy.protocol + ':',
auth: options.proxy.auth
};
}
exports.createHttpProxySettings = createHttpProxySettings;
function createHttpException(e) {
var _a;
let [url, status, data] = [(_a = e === null || e === void 0 ? void 0 : e.config) === null || _a === void 0 ? void 0 : _a.url, null, null, null];
if (e === null || e === void 0 ? void 0 : e.response) {
status = e.response.status;
data = e.response.data || null;
}
else if (e === null || e === void 0 ? void 0 : e.request) {
status = 408;
}
switch (status) {
case 400: return new bad_request_exception_1.WildduckBadRequestException(url, data, e === null || e === void 0 ? void 0 : e.stack);
case 404: return new not_found_exception_1.WildduckNotFoundException(url, data, e === null || e === void 0 ? void 0 : e.stack);
case 408: return new timeout_exception_1.WildduckTimeoutException(url, e === null || e === void 0 ? void 0 : e.stack);
case 422: return new unprocessable_entity_exception_1.WildduckUnprocessableEntityException(url, data, e === null || e === void 0 ? void 0 : e.stack);
case 500: return new internal_server_error_exception_1.WildduckInternalServerErrorException(url, data, e === null || e === void 0 ? void 0 : e.stack);
default: return new unknown_error_exception_1.WildduckUnknownErrorException(url, data, e === null || e === void 0 ? void 0 : e.stack);
}
}
exports.createHttpException = createHttpException;