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.log
s, 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
.