UNPKG

@nodesecure/scanner

Version:

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

101 lines 3.29 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(name, phase, fn) { const startedAt = this.#dateProvider.now(); try { const result = fn(); if (result instanceof Promise) { return result .then((res) => { this.#addApiStatVerbose(name, startedAt, this.#calcExecutionTime(startedAt)); 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, this.#calcExecutionTime(startedAt)); 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) { const stat = { name, startedAt, executionTime }; 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); 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