调用mysql

时间:2018-12-30 10:39:05

标签: mysql node.js express

需要您的帮助。我正在尝试为我的nodejs应用程序实现全局请求ID。为此,我使用express-http-context lib设置请求ID。但是当我的代码从mysql数据库访问数据时,它无法按预期工作。似乎 express-http-context 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

1 个答案:

答案 0 :(得分:1)

我希望此解决方案能够解决您的问题,并为有此问题的任何人节省很多时间

您可以只使用bindEmitter解决问题

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();
});