UNPKG

nestjs-otel

Version:
56 lines (55 loc) 2.31 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OtelMethodCounter = exports.OtelInstanceCounter = void 0; const opentelemetry_utils_1 = require("../../opentelemetry.utils"); const metric_data_1 = require("../metric-data"); /** * Create and increment a counter when a new instance is created * * @param originalClass */ const OtelInstanceCounter = (options) => (originalClass) => { const name = options?.name || `app.${originalClass.name}.instances.total`; const description = options?.description || `app.${originalClass.name} object instances total`; let counterMetric; const wrappedClass = class extends originalClass { constructor(...args) { if (!counterMetric) { counterMetric = (0, metric_data_1.getOrCreateCounter)(name, { description, ...options }); } counterMetric.add(1); super(...args); } }; Object.defineProperty(wrappedClass, "name", { value: originalClass.name }); (0, opentelemetry_utils_1.copyMetadataFromFunctionToFunction)(originalClass, wrappedClass); return wrappedClass; }; exports.OtelInstanceCounter = OtelInstanceCounter; /** * Create and increment a counter when the method is called */ const OtelMethodCounter = (options) => (target, propertyKey, descriptor) => { const className = target.constructor.name; const name = options?.name || `app.${className}.${propertyKey.toString()}.calls.total`; const description = options?.description || `app.${className}#${propertyKey.toString()} called total`; let counterMetric; const originalFunction = descriptor.value; if (!originalFunction) { return; } const wrappedFunction = function PropertyDescriptor(...args) { if (!counterMetric) { counterMetric = (0, metric_data_1.getOrCreateCounter)(name, { description, ...options }); } counterMetric.add(1); return originalFunction.apply(this, args); }; descriptor.value = new Proxy(originalFunction, { apply: (_, thisArg, args) => wrappedFunction.apply(thisArg, args), }); (0, opentelemetry_utils_1.copyMetadataFromFunctionToFunction)(originalFunction, descriptor.value); }; exports.OtelMethodCounter = OtelMethodCounter;