Synchronous Code in Node.js for URL Shortener Microservice

Synchronous Code in Node.js for URL Shortener Microservice
0

#1

My glitch is passing all the requirements for the URL Shortener Microservice project, except that in .send(), it only sends the original_url, and not the short_url as a JSON object.

It does store the short_url in the database, and it does redirect a user to that url when it’s entered. It just doesn’t show the short_url in the response page, because it doesn’t send().

Here's the piece of code where the issue is happening.
app.post("/api/shorturl/new", function (req, res, next) {
  req.newUrl = req.body.url;
  
  var jsonUrl = {"original_url": req.newUrl};
  var u = new urlPair(jsonUrl);
  u.save(function(err, data){
    if (err){
      throw err;
    }

    // query the database to see what the last short_url assigned was, 
    // in order to assign the new short_url number.  
    // from a library called mongoose-auto-increment.
    u.nextCount(function(err, count) {
      console.log("the count is " + count);
      req.shortUrl = count;
    });
  });
  
  next();
}, function(req, res){

  // sends the URL the user entered 
  // and the shortened version of the URL as a response to the form submission.
  // This should wait until req.shortUrl has been assigned in nextCount()
  res.send({"original_url": req.newUrl, "short_url": req.shortUrl});
});

After much console.logs, I’m pretty sure it’s because it sends (.send()) the JSON response to the https://distinct-dancer.glitch.me/api/shorturl/new path before deriving the new short_url (u.nextCount()) from the database.


That means those two functions are running asynchronously. I'm considering using the async library for node.js, to force them to run in the order they were written in (with the async.waterfall method), but I'm wondering if anyone knows a quick way native to node.js of doing that?
Fyi, nextCount() is a function that...

nextCount() is just querying the database to see what the last short_url assigned was, in order to assign the new short_url number. It’s from a library called mongoose-auto-increment.


#2

Try moving this just below req.shortUrl = count; I believe your correct in your theory. The callbacks are all asynchronous. so you have to do it inside a callback where you know you have the shorturl.

If you are using Mongoose, the save function is thenable so you can use promises instead of callbacks if you wanted to make it neater: http://www.summa.com/blog/avoiding-callback-hell-while-using-mongoose


#3

That worked! I just moved the line of code as you suggested, and I kept all the other code in place.

For future projects, I might try the instructions on promises in the article you sent. Thank you!