question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] Fetch request ID

See original GitHub issue

Im using below code to generate request ID:-

shared.module.ts

import {
  Module,
  HttpModule
} from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { APP_FILTER } from '@nestjs/core';
import { LoggerModule } from 'nestjs-pino';
import * as config from 'config';

import { CorrelationIdGeneratorService } from './services/helpers/generators/correlation-id-generator.service';


@Module({
  imports: [
    MongooseModule.forFeature([{ name: 'Device', schema: DeviceSchema }]),
    MongooseModule.forFeature([{ name: 'File', schema: FileSchema }]),
    HttpModule,
    LoggerModule.forRootAsync({
      providers: [
        CorrelationIdGeneratorService,
      ],
      inject: [CorrelationIdGeneratorService],
      useFactory: (correlationIdGeneratorService: CorrelationIdGeneratorService) => {
        return {
          pinoHttp: {
            genReqId: (request) => {
              correlationIdGeneratorService.generateCorrelationId(request);
              console.log('Im here 1',correlationIdGeneratorService.getCorrelationId());
              return correlationIdGeneratorService.getCorrelationId();
            },
            level: config.get('log.LEVEL'),
            useLevelLabels: true,
            base: null,
            timestamp: () => {
              return `, "time":"${new Date().toISOString()}"`;
            },
          },
        };
      }
    })
  ],
  providers: [
    CorrelationIdGeneratorService,
  ],
  exports: [
    CorrelationIdGeneratorService,
  ]
})
export class SharedModule { }

Now the issue is, i need to fetch the correlationId in another module for which i have exported the CorrelationIdGeneratorService from shared.module.ts and imported in my consuming modules.

Now in the consuming module im getting correlationId as undefined.

It seems that the object of CorrelationIdGeneratorService passed in loggermodule is different from the object passed in my consuming module. Please help, how can i share the singleton instance of correlation id throughout my code.

Below is the code for CorrelationIdGeneratorService correlation-id-generator.service.ts

import { Injectable } from '@nestjs/common';
import * as config from 'config';

import { UniqueIdGeneratorService } from './unique-id-generator.service';

@Injectable()
export class CorrelationIdGeneratorService {
    private correlationId: string;
    constructor(private readonly uniqueIdGeneratorService: UniqueIdGeneratorService) {}

    public generateCorrelationId(request: any) {
        this.correlationId = request?.headers?.[config.get('httpHeaders.CORRELATION_ID')] ||
        this.uniqueIdGeneratorService.generate(
            config.get('correlationId.VALID_CHARS'),
            config.get('correlationId.LENGTH')
        );
        console.log('Ammy 2', this.correlationId)
    }

    public getCorrelationId(): string {
        return this.correlationId;
    }
}

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:13 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
amit12coolcommented, Feb 7, 2020

This is resolved for me now. Solution:- Im generating new requestId in middleware for each request and updating the request object with the requestId property.

0reactions
iamoleggacommented, Feb 15, 2020

If you need some deps to create this function, you can assign it to variable, and export function that returns this variable

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to get the id after fetch call? - mysql - Stack Overflow
Try data[0].id, then according to the log you specified this should work, else post a picture of the log in the question. –...
Read more >
Fetch API - MDN Web Docs
The fetch() method takes one mandatory argument, the path to the resource you want to fetch. It returns a Promise that resolves to...
Read more >
Fetch - The Modern JavaScript Tutorial
Fetch. JavaScript can send network requests to the server and load new information whenever it's needed. For example, we can use a network ......
Read more >
How To Use the JavaScript Fetch API to Get Data - DigitalOcean
In this tutorial, you will create both GET and POST requests using the Fetch API. Prerequisites. To complete this tutorial, you will need...
Read more >
How to Use the JavaScript Fetch API to Get Data?
The Task here is to show how the Fetch API can be used to get data from an API. I will be taking...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found