declapract
Version:
A tool to declaratively define best practices, maintainable evolve them, and scalably enforce them.
40 lines • 1.73 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.withDurationReporting = void 0;
// tslint:disable no-console
const process_1 = require("process");
const logger_1 = require("../../utils/logger");
const roundToHundredths = (num) => Math.round(num * 100) / 100; // https://stackoverflow.com/a/14968691/3068233
/**
* a wrapper which reports how long it took to execute a function, after the function completes
*
* for example:
* ```ts
* const doSomethingThatMayTakeAWhile = withDurationReporting(
* 'doSomethingThatMayTakeAWhile',
* async (someArg: string, anotherArg: number) => {
* // your logic here
* }
* )
* ```
*/
const withDurationReporting = (title, logic, options = {
reportingThresholdSeconds: 1, // report on anything that takes more than 1 second, by default
log: ({ title, durationInSeconds }) => logger_1.log.debug(`⏲️ ${title} took ${durationInSeconds} seconds to execute`, {
title,
durationInSeconds,
}), // debug log by default
}) => {
return (async (...args) => {
const startTimeInNanoseconds = process_1.hrtime.bigint();
const result = await logic(...args);
const endTimeInNanoseconds = process_1.hrtime.bigint();
const durationInNanoseconds = endTimeInNanoseconds - startTimeInNanoseconds;
const durationInSeconds = roundToHundredths(Number(durationInNanoseconds) / 1e9); // https://stackoverflow.com/a/53970656/3068233
if (durationInSeconds >= options.reportingThresholdSeconds)
options.log({ title, durationInSeconds });
return result;
});
};
exports.withDurationReporting = withDurationReporting;
//# sourceMappingURL=withDurationReporting.js.map