Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lost context data using Typeorm logQuerySolw #70

Open
ahuijiLearning opened this issue Apr 13, 2022 · 1 comment
Open

Lost context data using Typeorm logQuerySolw #70

ahuijiLearning opened this issue Apr 13, 2022 · 1 comment

Comments

@ahuijiLearning
Copy link

ahuijiLearning commented Apr 13, 2022

// context.middleware.ts
export const ctxSession = cls.createNamespace('my session');

@Injectable()
export class RequestContextMiddleware implements NestMiddleware<Request, Response> {
  use(req: Request, res: Response, next: () => void) {
    ctxSession.run(() => {
      ctxSession.set('ctx', {
        req,
        res,
        startTime: new Date()
      });
      next();
    });

  }
}

// typeorm-logger.ts
export class OrmLogger implements Logger {
 logQuery(query: string, parameters?: any[], queryRunner?: QueryRunner) {
    console.log('startTime', ctxSession.get('ctx')?.startTime);   // output > startTime 2022-04-13T09:54:21.628Z
 }
 logQuerySlow(time: number, query: string, parameters?: any[], queryRunner?: QueryRunner) {
    console.log('startTime', ctxSession.get('ctx')?.startTime);   // output > startTime undefined
 }
}

Why does this problem occur and is there a solution?

@ahuijiLearning
Copy link
Author

// typeorm mysqlQueryRunner.js
new Promise(function (ok, fail){
  // ...
  this.driver.connection.logger.logQuery(query, parameters, this);
 // ...
 databaseConnection.query(query, parameters, function (err, raw) {
    // ...
    _this.driver.connection.logger.logQuerySlow(queryExecutionTime, query, parameters, _this);
    // ...
 }
}
I have looked at the source code for Typeorm to see if this callback method caused the loss, and if so, if there is a solution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant