Skip to content
Amir Hossein Seyhani edited this page Jul 22, 2017 · 8 revisions

Routing

At first we have to pull spring96 branch from repository

Then we have to add our routes Here we need two route:

  1. route to render the game page

     router.get("/game", showGamePageController)
    
  2. route to submit the user's high score

     router.post("/game", submitScoreController)
    

Get route

Here is our first contact with callbacks in JS.


Here we say the router if it see the "/game" path, it have to call showGamePageController function.

router.get("/game", showGamePageController)

Next let's implement showGamePageController function.

Here it has two arguments req(request)and res(response), which are objects that passed when called by router

At first we get username from request cookie. var savedUsername = req.cookies.username;

Then we have find high score of the user with this username (if exists in database) and then use render function. So we define a function for this:

function renderTetrisGamePageWithUserScore(err, storedUserScore) {
    res.render("game", {score: storedUserScore});
}

Post route

Here we catch post request:

router.post("/game", submitScoreController);

SubmitScoreController :

function submitScoreController(req, res){

We get user name and high score from request:

var savedUsername = req.body.username;
var score = req.body.score;

Now we need to somehow store user data wich is consist of username and high score, to handle this we have to defined Score model (database and models will be explained later) So at first we have to import score model:

var Score = require("../models/score");

Score have a findOne method :

findOne(options, callback)

It finds the document in database wich match options argument.

FindOne is a I/O function. it have to read all the documents in database to find the one which match the options. So we tell findOne to saveScoreInDataBase after it has find the matching.

saveScoreInDataBase is get called with err and storedScore arguements (storedScore is the found document).

 function saveScoreInDataBase(err, storedScore) {
	 if(storedScore){
			if(score > storedScore.score )
            storedScore.score = score;
          storedScore.save();
          return res.sendStatus(200)
    }else{
          var newScore = new Score({username:savedUsername,score:score});
          newScore.save();
          return res.sendStatus(200)
    }
}

If username already exist in database so we update the user score and save it and then we use sendStatus to tell client we have successfully accepted the request.(for successfull reqeust http status code 200 is used)

Here routing is completed. next we have to write code for our model.

Clone this wiki locally