tsvallender
tsvallender

Reputation: 2974

How can I set req.session from this scope?

I'm writing a Node.js application using Express and a PostgreSQL database using node-postgres. I want to look up the current user's username and real name based on their email, and set them in req.session. However, if I set them where I am in the code below, they are undefined when we leave that block (i.e. the first console.log statements print the correct info, the second set prints undefined. How can I solve this?

var client = new pg.Client(app.conString);
    var realname = "";
    var username = "";

    client.connect();
    var query = client.query(
        "SELECT * FROM users WHERE email = $1;",
        [req.session.email]
    );

    query.on('row', function(row) {
        req.session.realname = row.realname;
        req.session.username = row.username;
        console.log(req.session.realname);
        console.log(req.session.username);   
    });

    console.log(req.session.realname);
    console.log(req.session.username);

    query.on('end', function() {
        client.end();
    });

Upvotes: 0

Views: 185

Answers (1)

robertklep
robertklep

Reputation: 203484

The second pair of console.log will execute before the query-results are available (in the row event handler).

If your code is going to be used in an Express route, you would use something like this:

app.get('/', function(req, res) {
  var client = new pg.Client(app.conString);
  var realname = "";
  var username = "";

  client.connect();
  var query = client.query(
    "SELECT * FROM users WHERE email = $1;",
    [req.session.email]
  );

  query.on('row', function(row) {
    req.session.realname = row.realname;
    req.session.username = row.username;
  });

  query.on('end', function() {
    client.end();
    res.send(...); // <-- end the request by sending back a response
  });
});

An alternative for using the EventEmitter interface for node-postgres would be to just pass a callback to query (which looks better with Express IMHO):

  client.query(
    "SELECT * FROM users WHERE email = $1;", 
    [req.session.email], 
    function(err, results) {
      if (err)
         // handle error
      else
      if (results.length)
      {
        req.session.realname = results[0].realname;
        req.session.username = results[0].username;
      }
      res.send(...); // done
    });

Upvotes: 1

Related Questions