I’m still stuck in API & Microservices test no.3 : URL shorthener. I’ve installed all necessary packages, called them, etc, works fine. I then created my model :
var Schema = mongoose.Schema;
var urlSchema = new Schema({
url: {type:String, required:true}
});
var anUrl = mongoose.model('anUrl', urlSchema);
then handle the post request like so :
app.post('/api/shorturl/new', function(req, res){
const {myUrl} = req.body;
if(!validURL(myUrl)){//i have defined function validURL()
res.json({error: 'invalid URL'});
}else{
dns.lookup(myUrl, function (err, address, family) {
if(address===undefined){
res.json({error: 'invalid Hostname'});
}else{
//******code between these seems never get called********
/*I want to check wether or not a particular url have already been
recorded in the database. If it has, retrieve the short url. If it has not,
save it, then retreive the short url. However, the code below seems
unresponsive since the console.log part doesn't display anything at
glitch console*/
anUrl.find({url: myUrl}, function(error, urlFind){
console.log('find : ' + urlFind);//nothing displayed at console
if (error) return console.error(error);
console.log('find : ' + urlFind);//nothing displayed at console
/*I have also tried send the urlFind to some other function outside this route
handler. No response at all*/
});
//the code above seems does not called at all..
//******code between these seems never get called********
res.send('done : ' + myUrl);
}
});
}
})
The flow of the above snippet is as follow:
- validate the url, if it is not valid then
res.json({error: 'invalid URL'})
- If it is a valid url, then check if it is already registered at DNS server. If it has not, then respond with
res.json({error: 'invalid Hostname'})
- If it has not yet been registered at DNS server, then i’m going to check wether this particular submitted url address have already been a recorded document by means of
Model.find()
function. However, calling this function inside if branch seems does not do anything at all. Please have a look at the snippet above
This is my code so far (edit : link removed)