Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

returning instance of a pom client in a function and accessing it from another file lose context

I have a typescript class as follows:

const client = require('prom-client');


export default class Monitoring {

  // public client: any;
  private _logger: LoggingService;

  public constructor(logger: LoggingService) {
    // this._pomClient = client;
    this._logger = logger;
  }

  public async executePromClient() {
    this._logger.debug({message: `Returning prom client isnatnce`})
    const histogram = new client.Histogram({
      name: 'http_request_duration_seconds1',
      help: 'Duration of HTTP requests in seconds histogram',
      labelNames: ['method', 'handler', 'code'],
      buckets: [0.1, 5, 15, 50, 100, 500],
    });
    return histogram;
  }

  public async getPromClient() {
    this._logger.debug({message: `Returning prom client isnatnce`})
    return  client;

  }

he execute function works fine and not a problem however when I call getPromClient() in my server ts as follows:

const monitoring = new Monitoring(
  loggingService,
);
// const client = require('prom-client');
const client: any = monitoring.getPromClient();
// enable prom-client to expose default application metrics
const collectDefaultMetrics = client.collectDefaultMetrics;

I get

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TypeError: collectDefaultMetrics is not a function
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)

I am so confused I am just returning the client and trying to use in in sercer.ts
why is it not working?

>Solution :

You declared getPromClient() as async. That means it would return a Promise if you don’t await it. As you didn’t await anything within getPromClient(), simply remove the async will solve the problem.

public getPromClient() {
    this._logger.debug({message: `Returning prom client isnatnce`})
    return  client;
}

You probably don’t know what async mean and just declaring it everywhere which you shouldn’t. You can learn more about it here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading