将当前会话存储在变量中以在 MySQL 查询中使用

Storing current session in variable to use in MySQL Query

我想从当前用户 Session 中获取一些值并在 MySQL 查询中使用它们。我正在研究 Node.js 并使用 Redis 来管理会话。

文件Name:User.js

var sessionUtils = require('./../services/sessionUtils');
var Constants = require('./../constants');
var config = require('./../config');
var databaseUtils = require('./../services/databaseUtils');
var redisUtils = require('./../services/redisUtils');
var util = require('util');


showUserPage: function* (next){
    var queryString = "";
    var query = "";

    /*Do something to store session in variable*/       

    queryString = "select * from table where state='%s' and city='%s';";
    query = util.format(queryString,/*state variable here*/, /*city variable 
here*/);
    var user = yield databaseUtils.executeQuery(query);
    console.log(query);
    yield this.render('user', {
        user:user
    });
}

文件名:sessionUtils.js

var redisUtils = require('./redisUtils');
var uuid = require('uuid');
var thunkify = require('thunkify');

saveUserInSession: function(user, cookies) {
    var sessionId = uuid.v1();  // uuid: uniqe id every time
    var sessionObj = {user: user};
    redisUtils.setItemWithExpiry(sessionId,  JSON.stringify(sessionObj), 86400);    // 86400: for 1 day
    cookies.set("SESSION_ID", sessionId);
},

 getCurrentUser: thunkify(function(sessionId, callback) {
    var currentUser;
    if(sessionId) {
        redisUtils.getItemWithCallback(sessionId, function(err, res) {
            if(err) {
                logger.logError(err);
            }
            if(res == null) {
                callback(currentUser);
            } else {
                callback(err, JSON.parse(res).user);
            }
        });
    } else {
        callback(currentUser);
    }
})

我在 Login.js 文件中使用下面的行在会话中保存用户。

sessionUtils.saveUserInSession(results[0], this.cookies);

帮我解决这个问题。

我通过将以下代码替换为 /* Do something to store session in variable */

解决了这个问题
var sessionId = this.cookies.get("SESSION_ID");
var currentUser = yield sessionUtils.getCurrentUser(sessionId); 

并在 MySQL 查询中使用它,如下所示:

queryString = "select * from table where state='%s' and city='%s';";
query = util.format(queryString,currentUser.state, currentUser.city);

希望,它对其他人也有帮助。