@gqlts/runtime
Version:
Gqlts runtime client
98 lines • 3.82 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createFetcher = createFetcher;
const tslib_1 = require("tslib");
const axios_1 = tslib_1.__importDefault(require("axios"));
const form_data_1 = tslib_1.__importDefault(require("form-data"));
const batcher_1 = require("./client/batcher");
const extract_files_1 = require("./extract-files/extract-files");
const DEFAULT_BATCH_OPTIONS = {
maxBatchSize: 10,
batchInterval: 40,
};
function createFetcher(params) {
const { url = '', timeout = 100000, headers = {}, batch = false, ...rest } = params;
let { fetcherMethod, fetcherInstance } = params;
if (!url && !fetcherMethod) {
throw new Error('URL or fetcherMethod is required');
}
if (!fetcherInstance) {
fetcherInstance = axios_1.default.create({});
}
if (!fetcherMethod) {
fetcherMethod = async (body, config = {}) => {
const { clone, files } = (0, extract_files_1.extractFiles)(body);
const hasFiles = files?.size > 0;
let formData = undefined;
if (hasFiles) {
formData = new form_data_1.default();
// 1. First document is graphql query with variables
formData.append('operations', JSON.stringify(clone));
// 2. Second document maps files to variable locations
const map = {};
let i = 0;
files.forEach((paths) => {
map[i++] = paths;
});
formData.append('map', JSON.stringify(map));
// 3. all files not (same index as in map)
let j = 0;
for (const [file] of files) {
formData.append(`${j++}`, file, file.name);
}
}
const headersObject = {
...(hasFiles ? {} : { 'Content-Type': 'application/json' }),
...(typeof headers == 'function' ? await headers() : headers),
...(!!formData?.getHeaders && formData?.getHeaders()),
};
const fetchBody = hasFiles && formData ? formData : JSON.stringify(body);
return fetcherInstance({
url,
data: fetchBody,
method: 'POST',
headers: headersObject,
timeout,
withCredentials: true,
...rest,
...config,
})
.then((res) => {
if (res.status === 200) {
return res.data;
}
return {
data: null,
errors: [{ message: res.statusText, code: res.status, path: ['clientResponseNotOk'] }],
};
})
.catch((err) => {
return { data: null, errors: [{ message: err.message, code: err.code, path: ['clientResponseError'] }] };
});
};
}
if (!batch) {
return {
fetcherMethod: async (body, config) => {
if (!fetcherMethod) {
throw new Error('fetcher is required');
}
return fetcherMethod(body, config);
},
fetcherInstance,
};
}
const batcher = new batcher_1.QueryBatcher(async (batchedQuery, config) => {
if (!fetcherMethod) {
throw new Error('fetcher is not defined');
}
return fetcherMethod(batchedQuery, config);
}, batch === true ? DEFAULT_BATCH_OPTIONS : batch);
return {
fetcherMethod: async ({ query, variables }, config) => {
return batcher.fetch({ query, variables, config });
},
fetcherInstance,
};
}
//# sourceMappingURL=fetcher.js.map