@grafana/faro-web-sdk
Version:
Faro instrumentations, metas, transports for web.
92 lines • 3.3 kB
JavaScript
import { genShortID, Observable } from '@grafana/faro-core';
import { getUrlFromResource, isUrlIgnored } from '../../utils/url';
import { MESSAGE_TYPE_HTTP_REQUEST_END, MESSAGE_TYPE_HTTP_REQUEST_START } from './const';
const apiTypeFetch = 'fetch';
const apiTypeXhr = 'xhr';
/**
* Monitors if any http requests are in progress.
*/
export function monitorHttpRequests() {
const observable = new Observable();
function emitStartMessage(requestProps) {
observable.notify({
type: MESSAGE_TYPE_HTTP_REQUEST_START,
request: requestProps,
});
}
function emitEndMessage(requestProps) {
observable.notify({
type: MESSAGE_TYPE_HTTP_REQUEST_END,
request: requestProps,
});
}
monitorFetch({
onRequestStart: emitStartMessage,
onRequestEnd: emitEndMessage,
});
monitorXhr({
onRequestStart: emitStartMessage,
onRequestEnd: emitEndMessage,
});
return observable;
}
function monitorXhr({ onRequestStart, onRequestEnd, }) {
const originalOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function () {
const url = arguments[1];
const isIgnoredUrl = isUrlIgnored(url);
const method = arguments[0];
const requestId = genShortID();
// request has started to load data.
this.addEventListener('loadstart', function () {
if (!isIgnoredUrl) {
onRequestStart({ url, method, requestId, apiType: apiTypeXhr });
}
});
// transaction completes successfully.
this.addEventListener('load', function () {
if (!isIgnoredUrl) {
onRequestEnd({ url, method, requestId, apiType: apiTypeXhr });
}
});
this.addEventListener('error', function () {
if (!isIgnoredUrl) {
onRequestEnd({ url, method, requestId, apiType: apiTypeXhr });
}
});
this.addEventListener('abort', function () {
if (!isIgnoredUrl) {
onRequestEnd({ url, method, requestId, apiType: apiTypeXhr });
}
});
originalOpen.apply(this, arguments);
};
}
function monitorFetch({ onRequestEnd, onRequestStart, }) {
const originalFetch = window.fetch;
window.fetch = function () {
var _a, _b;
const url = (_a = getUrlFromResource(arguments[0])) !== null && _a !== void 0 ? _a : '';
const isIgnoredUrl = isUrlIgnored(url);
const method = ((_b = arguments[1]) !== null && _b !== void 0 ? _b : {}).method;
const requestId = genShortID();
if (!isIgnoredUrl) {
onRequestStart({ url, method, requestId, apiType: apiTypeFetch });
}
return originalFetch
.apply(this, arguments)
.then((response) => {
if (!isIgnoredUrl) {
onRequestEnd({ url, method, requestId, apiType: apiTypeFetch });
}
return response;
})
.catch((error) => {
if (!isIgnoredUrl) {
onRequestEnd({ url, method, requestId, apiType: apiTypeFetch });
}
throw error;
});
};
}
//# sourceMappingURL=httpRequestMonitor.js.map