express http context调用mysql后丢失

o3imoua4  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(381)

我需要你的帮助。我正在尝试为我的nodejs应用程序实现全局请求id。为此,我使用expresshttpcontext-lib来设置请求id。但是当我的代码从mysql数据库访问数据时,它不能像预期的那样工作。expresshttpcontext和mysql库使用的cls似乎存在兼容性问题。
示例代码和输出如下所示:

const app = require('express')();
const httpContext = require('express-http-context');
const mysql = require('mysql');
const { INTERNAL_SERVER_ERROR, OK, NOT_FOUND } = require('http-status-codes');
const http = require('http');
const uuidv4 = require('uuid/v4');

const pool = mysql.createPool({
  host: '127.0.0.1',
  port: 3306,
  user: 'root',
  password: 'Redhat@123',
  database: 'user',
  connectionLimit: 10,
});

pool.query('SELECT 1 + 1 AS solution', (error) => {
  if (error) {
    console.log('Unable to connect to MySQL:- ', error.message);
    process.exit(1);
  }
  console.log('MySQL PING is Working');
});

app.use(httpContext.middleware);
app.use((req, res, next) => {
  httpContext.set('requestId', uuidv4());
  console.log('request Id set is: ', httpContext.get('requestId'));
  next();
});

const getUserDetailsRepository = (userId, callback) => {
  console.log('inside getuserDetails repository for request id: ', httpContext.get('requestId'));
  pool.getConnection((connectionError, connection) => {
    if (connectionError) {
      console.log('got ConnError getuserDetails repository for request id: ', httpContext.get('requestId'));
      callback(connectionError);
    } else {
      const query = 'SELECT * from user where id = ?';
      connection.query(query, [userId], (queryError, results) => {
        connection.release();
        if (queryError) {
          console.log('got queryError getuserDetails repository for request id: ', httpContext.get('requestId'), queryError.message);
          callback(queryError);
        } else {
          console.log('Got response inside getuserDetails repository for request id: ', httpContext.get('requestId'));
          callback(null, results);
        }
      });
    }
  });
};

const userGetDetails = (req, res, next) => {
  const { userId } = req.params;
  console.log('inside getUserDetails controller for request id: ', httpContext.get('requestId'));
  getUserDetailsRepository(userId, (error, result) => {
    if (error) {
      console.log('got Error in getuserDetails controller for request id: ', httpContext.get('requestId'))
      res.sendStatus(INTERNAL_SERVER_ERROR);
    } else if (result) {
      console.log('Got response inside getuserDetails repository for request id: ', httpContext.get('requestId'));
      res.status(OK).json(result);
    } else {
      res.sendStatus(NOT_FOUND);
    }
  });
};

app.get('/user/:userId', userGetDetails);

const server = http.createServer(app);
server.listen(3000, () => console.log('Http server started listening on port'));

输出:

Http server started listening on port
MySQL PING is Working
request Id set is:  ea4895ab-8003-4d28-99aa-b03af7027ae8
inside getUserDetails controller for request id:  ea4895ab-8003-4d28-99aa-b03af7027ae8
inside getuserDetails repository for request id:  ea4895ab-8003-4d28-99aa-b03af7027ae8
Got response inside getuserDetails repository for request id:  undefined
Got response inside getuserDetails repository for request id:  undefined
xfb7svmp

xfb7svmp1#

我希望这个解决方案能解决你的问题,为任何有这个问题的人节省很多时间
你可以用bindemiter来解决这个问题

app.use((req, res, next) => {
  httpContext.ns.bindEmitter(req);
  httpContext.ns.bindEmitter(res);
  var requestId = req.headers["x-request-id"] || uuidv4();
  httpContext.set("requestId", requestId);
  console.log('request Id set is: ', httpContext.get('requestId'));
  next();
});

相关问题