0

Guys I am newbie in nodejs. My requirement is to save few user details from different tables for further process in my rest api project, after reading I got that I should save result from queries in session for further use. Here is my code ,I am not able to get session values outside the query result async call. What is the best way to save user details from different tables and use them for further queries.

method:

 if(sess.email)
      {
        console.log("session is valid");
          checkProfile.getRightOnCity(req.decoded , req.session);
          console.log("city session ::" ,  sess.cities); //i am getting this undeifned
      }

getRightOnCity:

var getRightOnCity = function getRightOnCity(req_decoded,req_session) {
    var myPromise = dbname(req_decoded);
    var user_id = getUserid(req_decoded);
    var details = getUserDetails(req_decoded);

    console.log("user details :: " , details);
    var cities = [];
    myPromise.then(function(myDBName) { 

        new_conn(myDBName).query("Select city_id from " + myDBName + ".rights_on_city where user_id="+user_id, function (err, res) {
        if(err) {
                    console.log("error: ", err);
                    result(null, err);
                }
                else{

                for(var i=0 ; i < res.length ; i++) {
                  cities.push(res[i].city_id);
                  req_session.cities = cities.join();

                  console.log("city::" , req_session.cities);
                  console.log("email inside get cities " ,  req_session.email);
                  req_session.save();

                }  


              }
            }); 

    });  

};
Nibha Jain
  • 7,742
  • 11
  • 47
  • 71

2 Answers2

2

First you need to RETURN the promise from the getRightOnCity function.

return myPromise.then and may need to wrap the DB call in promise as well.

function getRightOnCity(req_decoded, req_session) {
    var myPromise = dbname(req_decoded);
    var user_id = getUserid(req_decoded);
    var details = getUserDetails(req_decoded);

    console.log("user details :: ", details);
    var cities = [];
    return myPromise
        .then(function (myDBName) {
            return new Promise((resolve, rej)=>{ //<==here
                new_conn(myDBName).query("Select city_id from " + myDBName + ".rights_on_city where user_id=" + user_id, function (err, res) {
                    if (err) {
                        console.log("error: ", err);
                        result(null, err);
                        rej(err);
                    } else {
                        for (var i = 0; i < res.length; i++) {
                            cities.push(res[i].city_id);
                            req_session.cities = cities.join();

                            console.log("city::", req_session.cities);
                            console.log("email inside get cities ", req_session.email);
                            req_session.save();
                        }
                        resolve();
                    }
                });
            })
        });

};

Now, to use it you need .then or await the function.

if (sess.email) {
    console.log("session is valid");
    checkProfile
    .getRightOnCity(req.decoded, req.session)
    .then(()=>{
        console.log("city session ::", sess.cities);
    })
}

Note: It is not a good idea to mix Promise and callback

Aritra Chakraborty
  • 12,123
  • 3
  • 26
  • 35
  • Promise is used for another purpose not for saving cities in above code.. I want to save cities in session variable. I hope it is clear now – Nibha Jain Jun 24 '19 at 13:02
  • Yes, even then you need to return the Promise. Just I didn't see that the underlying code is not a promise. So wrapped it in promise and returned it. It will return the promise chain. – Aritra Chakraborty Jun 24 '19 at 13:07
  • Hi it working now .. actually i am completely new in nodejs and api development , what is the best way to save reuslts for further use in anywhere in project .. should I use session or it can be done by any other better way? – Nibha Jain Jun 24 '19 at 13:15
  • There are multiple ways, one obvious way is datastore like Redis. One is session. For requests you can add things in middlwares to add data in the request itself. You can use a cache service like memcached or persist the data in db. – Aritra Chakraborty Jun 24 '19 at 13:23
0

When you're passing req.session to getRightOnCity as req_session you're just passing a copy of the content of req.session. You should manipulate req.session directly from the first method, or via an ExpressJS middleware function.

0xCAP
  • 740
  • 4
  • 15