fix: refactor createFormData function

This commit is contained in:
Sanjai Kumar 2024-12-03 18:01:22 +05:30
parent fd22ff8962
commit f110d898f5

View File

@ -1,5 +1,5 @@
const os = require('os');
const { get, each, filter, compact, forOwn } = require('lodash');
const { get, each, filter, compact, forEach } = require('lodash');
const decomment = require('decomment');
const FormData = require('form-data');
const fs = require('fs');
@ -166,26 +166,34 @@ const mergeFolderLevelScripts = (request, requestTreePath, scriptFlow) => {
}
};
const createFormData = (datas, collectionPath) => {
const createFormData = (data, collectionPath) => {
// make axios work in node using form data
// reference: https://github.com/axios/axios/issues/1006#issuecomment-320165427
const form = new FormData();
forOwn(datas, (value, key) => {
if (typeof value == 'string') {
form.append(key, value);
forEach(data, (datum) => {
const { name, type, value } = datum;
if (type === 'text') {
if (Array.isArray(value)) {
value.forEach((val) => form.append(name, val));
} else {
form.append(name, value);
}
return;
}
const filePaths = value || [];
filePaths?.forEach?.((filePath) => {
let trimmedFilePath = filePath.trim();
if (type === 'file') {
const filePaths = value || [];
filePaths.forEach((filePath) => {
let trimmedFilePath = filePath.trim();
if (!path.isAbsolute(trimmedFilePath)) {
trimmedFilePath = path.join(collectionPath, trimmedFilePath);
}
if (!path.isAbsolute(trimmedFilePath)) {
trimmedFilePath = path.join(collectionPath, trimmedFilePath);
}
form.append(key, fs.createReadStream(trimmedFilePath), path.basename(trimmedFilePath));
});
form.append(name, fs.createReadStream(trimmedFilePath), path.basename(trimmedFilePath));
});
}
});
return form;
};
@ -435,11 +443,11 @@ const prepareRequest = (item, collection) => {
}
if (request.body.mode === 'multipartForm') {
axiosRequest.headers['content-type'] = 'multipart/form-data';
const params = {};
if (!contentTypeDefined) {
axiosRequest.headers['content-type'] = 'multipart/form-data';
}
const enabledParams = filter(request.body.multipartForm, (p) => p.enabled);
each(enabledParams, (p) => (params[p.name] = p.value));
axiosRequest.data = params;
axiosRequest.data = createFormData(enabledParams);
}
if (request.body.mode === 'graphql') {