1

I wrote a middle ware that update some variable that I have in cache, so if the data is supposed to be expired it will updated but actually is happening twice and is not chrome, I'm using firefox. This is my server js file(i commented mustache express as templates to be sure that it's not because of it):

const express = require('express') ;

const path = require('path');
var mustacheExpress = require('mustache-express');
var request = require('request');
var {updateAllDecks} = require('./utils/deck-request');
var cache = require('memory-cache');

const port = process.env.PORT || 3000;
var app = express();    

// Register '.html' extension with The Mustache Express
app.engine('html', mustacheExpress());
app.set('view engine','mustache');

app.set('views', __dirname + '/views');

//const publicPath = path.join(__dirname, '/public');
//app.use('/', express.static(publicPath));

app.use(function (req, res, next) {
  debugger;
  updateAllDecks(next);
})

app.get('/', (req, res) => {
     res.send('hola');
});

app.listen(port, () => {
  console.log(`Server is up on port ${port}`);
});

So when I go to '/' through the browser updateAllDecks() should be called:

var rp = require('request-promise-native');
var cache = require('memory-cache');
var {Deck} = require('../classes/deck');
var cacheDeck = require('./cache-decks');
var moment = require('moment');


var updateDeck =  async (set,resolve) => {
  //console.log(`${cacheDeck.getCachedExpirationDate(set)}  > ${moment(Date.now()).unix()}`);

    if (cacheDeck.getCachedExpirationDate(set) > moment(Date.now()).unix()) {
      //let deck =  await getDeckCached(set);
      console.log('Cached Deck Back');
      resolve();

    } else {
      let url = `https://playartifact.com/cardset/${set}/`;
      console.log('Getting URL');
      response = await  rp({url:url, json: true});
      var deck = new Deck(set, response.expire_time);
      getDeckRequest(deck,response,resolve)

    }


}

var getDeckRequest =  async (deck, body,resolve) => {
    console.log('Caching deck', deck);
    response = await rp({url:body.cdn_root + body.url.substring(1), json: true});
    deck.setName(response.card_set.set_info.name.english);
    deck.setCards(response.card_set.card_list);
    cacheDeck.addDeck(deck);
    console.log(cacheDeck.getCachedDecksNames());
    resolve();

}

var getDeckCached = (id) => {
  return new Promise((resolve,reject) =>  {
      resolve(cacheDeck.getCachedDeckById(id));
  });
}

var updateAllDecks = (callback) => {

  let decks = [0,1];
  var request = decks.map((deck) =>  {
    return new Promise( (resolve) => {
       updateDeck(deck,resolve);
    });

  });

  Promise.all(request).then(() => {
    callback();
    console.log('Finished');
  });
};

module.exports = {updateAllDecks}

The callback(); in the updateAllDecks() Function is the next() call to advance to show the page.

  • Hi @Roberto, it seems that you are from Chile, and me too :) ...what I think it's the cause of that issue are some misconceptions on how to serve nodejs content. You are using `express` and `http` together and you shouldn't. You should use `express` or `http`, since `express` uses the http module under the hood. You should have `app.listen` and that's it. Please take a look at this Q&A for more clarification: https://stackoverflow.com/questions/35167824/difference-between-a-server-with-http-createserver-and-a-server-using-express-in – Hackerman Nov 21 '18 at 19:56
  • Also https://developer.mozilla.org/es/docs/Learn/Server-side/Express_Nodejs/Introduction – Hackerman Nov 21 '18 at 19:57
  • thank you @Hackerman for those tips, bit still causing to run the middleware twice. it runs before showing the response and after it. – Roberto Matus Nov 21 '18 at 20:09
  • Mira Roberto, lo que pasa es que estás usando estas dos cosas para hacer lo mismo `const express = require('express'); const http = require('http');`. Acá sólo debieses usar express y no los dos. Por ejemplo, la escoba te queda en esta línea `var server = http.createServer(app);`...eso está super mal. Express no necesita del módulo `http`, el ya lo usa en el background, me captas? – Hackerman Nov 21 '18 at 20:13
  • 1
    @Hackerman si te entiendo perfectamente y lo modifiqué solo para usar express y continua ejecutándose 2 veces. – Roberto Matus Nov 21 '18 at 20:16
  • Just for testing purposes, stop the nodejs server and try again...ps: se ve excelente el juego y en steam, congrats! – Hackerman Nov 21 '18 at 20:23
  • 1
    @Hackerman still, i'm going to try adding a simple middleware, maybe it has something to do with promises and next is being called twice. The game looks amazing looking forward for next week launch! – Roberto Matus Nov 21 '18 at 20:31
  • That's the other hunch that I had....maybe some async promises related issue. Anyway, this question also helped you to have a better undertanding on express, imho. Glad to help :) – Hackerman Nov 21 '18 at 20:37
  • 1
    @Hackerman found it!! it was a call to a favicon, thank you a lot for your time – Roberto Matus Nov 22 '18 at 23:11

1 Answers1

9

Added this line of code in the middleware function to know what was the call.

console.log(req.method, req.path)

Turns out that was the call from the browser to the server to get the favicon that made express to call the middleware.