All files transport.js

95.65% Statements 22/23
85.71% Branches 6/7
92.31% Functions 12/13
95.24% Lines 20/21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76                  21x 21x   21x     12x 11x   1x     21x       18x           1x 6x   6x     6x     1x       21x                   21x 9x   9x       21x   9x     7x                  
export function sendReport(payload, transportOpts, attempt = 0) {
	const {
		send,
		payloadMiddleware,
		fetchOptions,
		successHandler,
		retryCount,
		failedTryHandler,
		failedReportHandler,
	} = transportOpts;
	const transformedPayload = payloadMiddleware(payload);
 
	send(transformedPayload, fetchOptions)
		.then(successHandler)
		.catch((errorResponse) => {
			if (attempt < retryCount) {
				failedTryHandler(errorResponse, sendReport, payload, transportOpts, attempt);
			} else {
				failedReportHandler(errorResponse, payload, transportOpts);
			}
		});
	return transformedPayload;
}
 
function defaultPayloadMiddleware(payload) {
	return {
		time: new Date(),
		...payload,
	};
}
 
const defaultHandlers = {
	success: (response) => { console.info('Logging: reported', response); },
	failedTry: function failedTry(error, report, payload, transportOpts, attempt) {
		setTimeout(() => {
			report(payload, transportOpts, attempt + 1);
		}, transportOpts.retryTimeout);
		console.warn('Logging: Looks like logging host is unreachable, ' +
			`retrying in ${transportOpts.retryTimeout / 1000} seconds`);
	},
	failedReport: (error) => { console.error('Logging: unable to send reports', error); },
};
 
function getFetchPayload(payload, otherFetchOptions = {}) {
	return Object.assign({
		method: 'POST',
		headers: { 'Content-Type': 'application/json' },
	}, {
		body: JSON.stringify({ '@message': payload }),
		...otherFetchOptions,
	});
}
 
function shouldBeOk(response) {
	if (!response.ok) {
		throw new Error(response);
	}
	return response;
}
 
function getDefault(url) {
	return (payload, fetchOptions = {}) => fetch(url, getFetchPayload(payload, fetchOptions))
		.then(shouldBeOk)
		.then(response => response.text());
}
 
export const getDefaultTransport = url => ({
	send: getDefault(url),
	successHandler: defaultHandlers.success,
	failedTryHandler: defaultHandlers.failedTry,
	failedReportHandler: defaultHandlers.failedReport,
	payloadMiddleware: defaultPayloadMiddleware,
	retryCount: 2,
	retryTimeout: 60 * 1000,
});