graphql-request
Version:
Minimal GraphQL client supporting Node and browsers for scripts or simple apps
53 lines • 2.16 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var extract_files_1 = require("extract-files");
var form_data_1 = __importDefault(require("form-data"));
/**
* Duck type if NodeJS stream
* https://github.com/sindresorhus/is-stream/blob/3750505b0727f6df54324784fe369365ef78841e/index.js#L3
*/
var isExtractableFileEnhanced = function (value) {
return extract_files_1.isExtractableFile(value) ||
(value !== null && typeof value === 'object' && typeof value.pipe === 'function');
};
/**
* Returns Multipart Form if body contains files
* (https://github.com/jaydenseric/graphql-multipart-request-spec)
* Otherwise returns JSON
*/
function createRequestBody(query, variables, operationName) {
var _a = extract_files_1.extractFiles({ query: query, variables: variables, operationName: operationName }, '', isExtractableFileEnhanced), clone = _a.clone, files = _a.files;
if (files.size === 0) {
if (!Array.isArray(query)) {
return JSON.stringify(clone);
}
if (typeof variables !== 'undefined' && !Array.isArray(variables)) {
throw new Error('Cannot create request body with given variable type, array expected');
}
// Batch support
var payload = query.reduce(function (accu, currentQuery, index) {
accu.push({ query: currentQuery, variables: variables ? variables[index] : undefined });
return accu;
}, []);
return JSON.stringify(payload);
}
var Form = typeof FormData === 'undefined' ? form_data_1.default : FormData;
var form = new Form();
form.append('operations', JSON.stringify(clone));
var map = {};
var i = 0;
files.forEach(function (paths) {
map[++i] = paths;
});
form.append('map', JSON.stringify(map));
i = 0;
files.forEach(function (paths, file) {
form.append("" + ++i, file);
});
return form;
}
exports.default = createRequestBody;
//# sourceMappingURL=createRequestBody.js.map
;