Skip to content

Commit

Permalink
chore: wrapTimer function types (#8428)
Browse files Browse the repository at this point in the history
This gives us better types for our wrapTimer function.

Maybe the type `(args: any) => any` could also be improved

---------

Co-authored-by: Nuno Góis <[email protected]>
  • Loading branch information
gastonfournier and Nuno Góis authored Oct 15, 2024
1 parent e4cfb29 commit e22f6a0
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export default class ClientFeatureToggleReadModel

constructor(db: Db, eventBus: EventEmitter) {
this.db = db;
this.timer = (action) =>
this.timer = (action: string) =>
metricsHelper.wrapTimer(eventBus, DB_TIME, {
store: 'client-feature-toggle-read-model',
action,
Expand Down
2 changes: 1 addition & 1 deletion src/lib/features/frontend-api/frontend-api-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export default class FrontendAPIController extends Controller {
this.logger = config.getLogger('frontend-api-controller.ts');
this.services = services;

this.timer = (functionName) =>
this.timer = (functionName: string) =>
metricsHelper.wrapTimer(config.eventBus, FUNCTION_TIME, {
className: 'FrontendAPIController',
functionName,
Expand Down
29 changes: 20 additions & 9 deletions src/lib/util/metrics-helper.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,31 @@
/* eslint-disable no-param-reassign */
import type EventEmitter from 'events';
import timer from './timer';

// wrapTimer keeps track of the timing of a async operation and emits
// a event on the given eventBus once the operation is complete
//
// the returned function is designed to be used as a .then(<func>) argument.
// It transparently passes the data to the following .then(<func>)
// the returned function is designed to stop the timer and emit the event
//
// usage: promise.then(wrapTimer(bus, type, { payload: 'ok' }))
const wrapTimer: (EventEmitter, string, object) => (any) => any = (
eventBus,
event,
args = {},
// Usage:
// Define the timer function. It can be done once per class.
// this.timer = (action: string) =>
// metricsHelper.wrapTimer(eventBus, DB_TIME, {
// store: 'client-feature-toggle-read-model',
// action,
// });
//
// Before performing an operation, start the timer:
// const stopTimer = this.timer(`timer-name`);
// // perform operation and then stop timer
// stopTimer();

const wrapTimer = (
eventBus: EventEmitter,
event: string,
args: Record<string, unknown> = {},
) => {
const t = timer.new();
return (data) => {
return (data: unknown) => {
args.time = t();
eventBus.emit(event, args);
return data;
Expand Down

0 comments on commit e22f6a0

Please sign in to comment.