0

I'm coding a web based game and I'd like to share variables within every view.

Every user has created their own race and every race has lots of variables inside. ie - commodities{money, energy,...} planets{owned, built,...}

I want to show those values on every page after a user logs in. These values are going to change every time a user performs an action.

for no I'm using helper module

dbValues.commodities = function(userId, callback){
    Race.findOne({"owner.id" : userId}, function(err, race){
        if(err){
            console.log(err)
        } else {
            var money = race.commodities.money;
            var energy = race.commodities.energy;
            var metals = race.commodities.metals;
            var techs = race.commodities.techs;
            var soldiers = race.commodities.soldiers;
            callback(money, energy, metals, techs, soldiers);
        }
    });
}

I'd like to avoid calling this function on every route as these are only values for commodities.

Can you give me some advice how to do that?

I want to use it in partial what will be same on every page after login. Is there a way to place it for partial? For other pages I want to show them specially I can call this function in router.

Glen Pierce
  • 4,401
  • 5
  • 31
  • 50
SLUNlCKO
  • 21
  • 4

1 Answers1

0

You could use express-session :

var app=require("express")();
var sess=require("express-session");
app.use(sess({secret:"somerandom"});

Now every Express.request has a session property, wich is persistent per user:

app.get("/",function(req,res){
  if(!req.session){
    Race.findOne({"owner.id" : userId}, function(err, race){
    if(err){
        console.log(err)
    } else {
        req.session= race.commodities;
        res.end(race.commodities.money);
    }
   });
  }else{
   res.end(req.session.commodities.money);
}

So at the first request, the database is requested and the data is cached. On the second request, it gets the stored data without reloading from the db.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151