Skip to content

Commit

Permalink
add monitorMethod decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonLdj committed Jul 11, 2022
1 parent 3247358 commit 157744c
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
16 changes: 15 additions & 1 deletion example/run.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import 'dotenv/config';

import {setGlobalInstance, StatsdPlugin, monitored, Monitor, increment} from '../src';
import {setGlobalInstance, StatsdPlugin, monitored, Monitor, increment, monitorMethod} from '../src';

setGlobalInstance(
new Monitor({
Expand Down Expand Up @@ -104,3 +104,17 @@ increment('metric1');
// Increment with type restriction
type Color = 'red' | 'orange' | 'green';
increment<Color>('red');

// monitor method using decorator
class Person {
firstName: string = 'Jon';
lastName: string = 'Doe';

@monitorMethod('person', {logErrorAsInfo: true})
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
}
const person = new Person();
const name = person.getFullName();
console.log(`person's name is ${name}`);
10 changes: 10 additions & 0 deletions src/globalInstance.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Monitor from './Monitor';
import {MonitoredOptions} from './types';

let instance: Monitor | undefined;

Expand All @@ -15,10 +16,19 @@ export function getGlobalInstance(): Monitor {
}

export const monitored: Monitor['monitored'] = (...args) => getGlobalInstance().monitored(...args);

/**
* @deprecated since version 2.0
*/
export const getStatsdClient: Monitor['getStatsdClient'] = (...args) => getGlobalInstance().getStatsdClient(...args);
export const increment: Monitor['increment'] = (...args) => getGlobalInstance().increment(...args);
export const gauge: Monitor['gauge'] = (...args) => getGlobalInstance().gauge(...args);
export const timing: Monitor['timing'] = (...args) => getGlobalInstance().timing(...args);

export const monitorMethod = <T>(prefix?: string, options: MonitoredOptions<T> = {}) => {
return function (_target: Object, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
const metricName = `${prefix}${prefix ? '.' : ''}${propertyKey}`;
descriptor.value = monitored(metricName, originalMethod, options);
};
};
5 changes: 3 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@
"lib": ["dom", "es2017"],
"skipLibCheck": true,
"noImplicitAny": false,
"useUnknownInCatchVariables": false
"useUnknownInCatchVariables": false,
"experimentalDecorators": true
},
"include": ["src/**/*", "types/*.d.ts"],
"include": ["src/**/*", "types/*.d.ts", "example/**/*"],
"exclude": ["__tests__", "dist"]
}

0 comments on commit 157744c

Please sign in to comment.