UNPKG

@nodesecure/scanner

Version:

A package API to run a static analysis of your module's dependencies.

119 lines 3.79 kB
// Import Node.js Dependencies import { EventEmitter } from "node:events"; // Import Third-party Dependencies import { isHTTPError } from "@openally/httpie"; // Import Internal Dependencies import { SystemDateProvider } from "./DateProvider.class.js"; import { Logger } from "./logger.class.js"; export class StatsCollector { #logger; #dateProvider; #apiCalls = []; #startedAt; #errors = []; #isVerbose; constructor(providers, options) { const { dateProvider = new SystemDateProvider(), logger = new Logger() } = providers; this.#logger = logger; this.#dateProvider = dateProvider; this.#startedAt = this.#dateProvider.now(); this.#isVerbose = options.isVerbose; } track(options) { const { name, phase, fn, onSuccess } = options; const startedAt = this.#dateProvider.now(); try { const result = fn(); if (result instanceof Promise) { return result .then((res) => { this.#addApiStatVerbose({ name, startedAt, executionTime: this.#calcExecutionTime(startedAt), result: res, onSuccess }); return res; }) .catch((err) => { const executionTime = this.#calcExecutionTime(startedAt); this.#addError({ name, err, executionTime, phase }); this.#apiCalls.push({ name, startedAt, executionTime }); throw err; }); } this.#addApiStatVerbose({ name, startedAt, executionTime: this.#calcExecutionTime(startedAt), result, onSuccess }); return result; } catch (err) { const executionTime = this.#calcExecutionTime(startedAt); this.#apiCalls.push({ name, startedAt, executionTime }); this.#addError({ name, err, executionTime, phase }); throw err; } } #calcExecutionTime(startedAt) { return this.#dateProvider.now() - startedAt; } #addApiStatVerbose({ name, startedAt, executionTime, result, onSuccess }) { const stat = { name, startedAt, executionTime }; if (onSuccess) { onSuccess(result, stat); } this.#apiCalls.push(stat); if (this.#isVerbose) { this.#logger.emit("stat", stat); } } #addError(params) { const { name, executionTime, err, phase } = params; const error = { name }; if (err instanceof Error) { error.message = err.message; error.stack = err.stack; } if (isHTTPError(err)) { error.statusCode = err.statusCode; } this.#errors.push(error); if (this.#isVerbose) { this.#logger.emit("error", { ...error, executionTime }, phase); } } getStats() { return { startedAt: this.#startedAt, executionTime: this.#dateProvider.now() - this.#startedAt, apiCalls: this.#apiCalls, apiCallsCount: this.#apiCalls.length, errorCount: this.#errors.length, errors: this.#errors }; } } //# sourceMappingURL=StatsCollector.class.js.map