Jeff-Lewis / cls-hooked

cls-hooked : CLS using AsynWrap or async_hooks instead of async-listener for node 4.7+

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Lost context data using Typeorm logQuerySolw

ahuijiLearning opened this issue · comments

// 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?

// 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