debian-mirror-gitlab/app/assets/javascripts/lib/utils/axios_startup_calls.js

75 lines
1.8 KiB
JavaScript
Raw Normal View History

2020-07-28 23:09:34 +05:30
import { isEmpty } from 'lodash';
import { mergeUrlParams } from './url_utility';
// We should probably not couple this utility to `gon.gitlab_url`
// Also, this would replace occurrences that aren't at the beginning of the string
2021-03-08 18:12:59 +05:30
const removeGitLabUrl = (url) => url.replace(gon.gitlab_url, '');
2020-07-28 23:09:34 +05:30
2021-03-08 18:12:59 +05:30
const getFullUrl = (req) => {
2020-07-28 23:09:34 +05:30
const url = removeGitLabUrl(req.url);
2021-01-03 14:25:43 +05:30
return mergeUrlParams(req.params || {}, url, { sort: true });
2020-07-28 23:09:34 +05:30
};
2020-11-24 15:15:51 +05:30
const handleStartupCall = async ({ fetchCall }, req) => {
const res = await fetchCall;
if (!res.ok) {
throw new Error(res.statusText);
}
const fetchHeaders = {};
res.headers.forEach((val, key) => {
fetchHeaders[key] = val;
});
const data = await res.clone().json();
Object.assign(req, {
adapter: () =>
Promise.resolve({
data,
status: res.status,
statusText: res.statusText,
headers: fetchHeaders,
config: req,
request: req,
}),
});
};
2021-03-08 18:12:59 +05:30
const setupAxiosStartupCalls = (axios) => {
2020-07-28 23:09:34 +05:30
const { startup_calls: startupCalls } = window.gl || {};
if (!startupCalls || isEmpty(startupCalls)) {
return;
}
2020-11-24 15:15:51 +05:30
const remainingCalls = new Map(Object.entries(startupCalls));
2021-03-08 18:12:59 +05:30
const interceptor = axios.interceptors.request.use(async (req) => {
2020-07-28 23:09:34 +05:30
const fullUrl = getFullUrl(req);
2020-11-24 15:15:51 +05:30
const startupCall = remainingCalls.get(fullUrl);
if (!startupCall?.fetchCall) {
return req;
}
try {
await handleStartupCall(startupCall, req);
} catch (e) {
// eslint-disable-next-line no-console
console.warn(`[gitlab] Something went wrong with the startup call for "${fullUrl}"`, e);
}
remainingCalls.delete(fullUrl);
if (remainingCalls.size === 0) {
axios.interceptors.request.eject(interceptor);
2020-07-28 23:09:34 +05:30
}
return req;
});
};
export default setupAxiosStartupCalls;