axios-light-my-request-adapter
Version:
Axios adapter for Light my Request
267 lines • 12.1 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLightMyRequestAdapterFromFastify = exports.createLightMyRequestAdapter = void 0;
const axios_1 = require("axios");
const light_my_request_1 = require("light-my-request");
const stream_1 = require("stream");
const url_1 = __importDefault(require("url"));
const axios_core_1 = require("./axios-core");
const axios_error_1 = require("./axios-error");
const axios_helpers_1 = require("./axios-helpers");
const utils = __importStar(require("./axios-utils"));
/**
* Create an `AxiosAdapter` that will inject requests/responses into `dispatchFunc` via Light my
* Request.
*
* @param dispatchFunc - Listener function. The same as you would pass to `http.createServer` when
* making a node HTTP server.
* @param opts - Additional options
* @returns An `AxiosAdapter`
*/
function createLightMyRequestAdapter(dispatchFunc, opts = {}) {
return function lightMyRequestAdapter(config) {
return new Promise((resolvePromise, rejectPromise) => {
let onCanceled;
let timeout;
function done() {
if (config.cancelToken) {
config.cancelToken.unsubscribe(onCanceled);
}
if (config.signal) {
config.signal.removeEventListener("abort", onCanceled);
}
if (timeout) {
clearTimeout(timeout);
}
}
function resolve(value) {
done();
resolvePromise(value);
}
function reject(value) {
done();
rejectPromise(value);
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const data = config.data;
const headers = config.headers ?? {};
const headerNames = {};
Object.keys(headers).forEach(function storeLowerName(name) {
headerNames[name.toLowerCase()] = name;
});
// support for https://www.npmjs.com/package/form-data api
// eslint-disable-next-line @typescript-eslint/unbound-method
if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) {
Object.assign(headers, data.getHeaders());
}
else if (data && !utils.isStream(data)) {
if (config.maxBodyLength &&
config.maxBodyLength > -1 &&
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
data.length > config.maxBodyLength) {
reject(new axios_1.AxiosError("Request body larger than maxBodyLength limit", axios_1.AxiosError.ERR_BAD_REQUEST, config));
return;
}
}
// HTTP basic authentication
let auth = undefined;
if (config.auth) {
const username = config.auth.username || "";
const password = config.auth.password || "";
auth = username + ":" + password;
}
// Parse url
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const fullPath = (0, axios_core_1.buildFullPath)(config.baseURL, config.url);
const parsed = url_1.default.parse(fullPath);
if (!auth && parsed.auth) {
const urlAuth = parsed.auth.split(":");
const urlUsername = urlAuth[0] || "";
const urlPassword = urlAuth[1] || "";
auth = urlUsername + ":" + urlPassword;
}
if (auth) {
if (headerNames.authorization) {
delete headers[headerNames.authorization];
}
headers.authorization = "Basic " + Buffer.from(auth).toString("base64");
}
try {
const params = (0, axios_helpers_1.buildParams)(config.params, config.paramsSerializer).replace(/^\?/, "");
if (parsed.search != null) {
parsed.search += "&" + params;
}
else {
parsed.search = params;
}
}
catch (err) {
const customErr = new Error(err.message);
customErr.config = config;
customErr.url = config.url;
customErr.exists = true;
reject(customErr);
return;
}
if (config.maxRedirects != null) {
reject(new Error("maxRedirects not supported"));
return;
}
if (config.socketPath != null) {
reject(new Error("socketPath not supported"));
return;
}
if (config.proxy != null) {
reject(new Error("proxy not supported"));
return;
}
const controller = new AbortController();
(0, light_my_request_1.inject)(dispatchFunc, {
url: url_1.default.format(parsed),
method: config.method?.toUpperCase(),
headers: headers,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
payload: config.data,
server: opts.server,
remoteAddress: opts.remoteAddress,
signal: controller.signal,
}, (err, res) => {
if (err) {
reject((0, axios_error_1.axiosErrorFrom)(err, null, config, res?.raw.req));
return;
}
const response = {
status: res.statusCode,
statusText: res.statusMessage,
headers: res.headers,
config: config,
request: res.raw.req,
data: undefined,
};
if (config.responseType === "stream") {
const responseData = new stream_1.Readable();
responseData.push(res.rawPayload);
responseData.push(null);
response.data = responseData;
(0, axios_core_1.settle)(resolve, reject, response);
}
else {
// make sure the content length is not over the maxContentLength if specified
if (config.maxContentLength &&
config.maxContentLength > -1 &&
res.rawPayload.length > config.maxContentLength) {
// stream.destoy() emit aborted event before calling reject() on Node.js v16
reject(new axios_1.AxiosError(`maxContentLength size of ${config.maxContentLength} exceeded`, axios_1.AxiosError.ERR_BAD_RESPONSE, config, res.raw.req));
return;
}
try {
if (config.responseType === "arraybuffer") {
response.data = res.rawPayload;
}
else {
let responseData = res.payload;
if (!config.responseEncoding ||
config.responseEncoding === "utf8") {
responseData = utils.stripBOM(responseData);
}
response.data = responseData;
}
}
catch (err) {
reject((0, axios_error_1.axiosErrorFrom)(err, null, config, response.request, response));
}
(0, axios_core_1.settle)(resolve, reject, response);
}
});
// Handle request timeout
if (config.timeout) {
let timeoutMs;
if (config.timeout) {
// This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
timeoutMs = parseInt(config.timeout, 10);
if (isNaN(timeoutMs)) {
reject(new axios_1.AxiosError("error trying to parse `config.timeout` to int", axios_1.AxiosError.ERR_BAD_OPTION_VALUE, config
// req
));
return;
}
timeout = setTimeout(function handleRequestTimeout() {
controller.abort();
const transitional = config.transitional || {
clarifyTimeoutError: false,
};
reject(new axios_1.AxiosError(`timeout of ${timeoutMs} ms exceeded`, transitional.clarifyTimeoutError
? axios_1.AxiosError.ETIMEDOUT
: axios_1.AxiosError.ECONNABORTED, config
// req
));
}, timeoutMs);
}
}
if (config.cancelToken || config.signal) {
// Handle cancellation
onCanceled = function (cancel) {
if (controller.signal.aborted)
return;
controller.abort();
reject(!cancel || (cancel && cancel.type) ? new axios_1.CanceledError() : cancel);
};
config.cancelToken &&
config.cancelToken.subscribe(onCanceled);
if (config.signal) {
config.signal.aborted
? onCanceled()
: config.signal.addEventListener("abort", onCanceled);
}
}
});
};
}
exports.createLightMyRequestAdapter = createLightMyRequestAdapter;
/**
* Create an `AxiosAdapter` that will inject requests/responses into the Fastify `instance` via
* Light my Request.
*
* @param instance - A Fastify instance.
* @param opts - Additional options
* @returns An `AxiosAdapter`
*/
function createLightMyRequestAdapterFromFastify(instance, opts = {}) {
return createLightMyRequestAdapter((req, res) => {
instance.ready((err) => {
if (err) {
res.emit("error", err);
return;
}
instance.routing(req, res);
});
}, opts);
}
exports.createLightMyRequestAdapterFromFastify = createLightMyRequestAdapterFromFastify;
//# sourceMappingURL=index.js.map