UNPKG

declapract

Version:

A tool to declaratively define best practices, maintainable evolve them, and scalably enforce them.

49 lines 2.45 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.withDurationReporting = void 0; // tslint:disable no-console const process_1 = require("process"); const logger_1 = require("../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 ((...args) => __awaiter(void 0, void 0, void 0, function* () { const startTimeInNanoseconds = process_1.hrtime.bigint(); const result = yield 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