nestjs-otel
Version:
NestJS OpenTelemetry Library
54 lines (53 loc) • 2.23 kB
JavaScript
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 = `app_${originalClass.name}_instances_total`;
const 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 = `app_${className}_${propertyKey.toString()}_calls_total`;
const description = `app_${className}#${propertyKey.toString()} called total`;
let counterMetric;
const originalFunction = descriptor.value ?? (() => { });
const wrappedFunction = function PropertyDescriptor(...args) {
if (!counterMetric) {
counterMetric = (0, metric_data_1.getOrCreateCounter)(name, { description, ...options });
}
counterMetric.add(1);
// @ts-ignore
return originalFunction.apply(this, args);
};
descriptor.value = new Proxy(originalFunction, {
apply: (_, thisArg, args) => {
return wrappedFunction.apply(thisArg, args);
},
});
(0, opentelemetry_utils_1.copyMetadataFromFunctionToFunction)(originalFunction, descriptor.value);
};
exports.OtelMethodCounter = OtelMethodCounter;
;