Hi guys, I was doing this challenge, and here is post’s Handler method. It is working, but somehow, the code structure does not look nice. I feel that it is not the right way to solve but some workarround that I’ve found. All my logic is stored under the dns.lookup and that is what is bothering me, for I could not find a way to take the error object out of the inner callback and use it in an “if” statement outside the dns.lookup method.
I tought about storing it in a variable outside of the callback function, but it seems more like a workaround than a canonical solution and I did not make dns.lookup a separate middleware because I don’t feel like it is the aproppiate solution, but maybe it is.
I understand that usually there are many ways of solving a problem, but again, there must be a more suited one in this case.
Would you mind taking a look at it, and letting me know what would have been a more conventional or appropriate way of making handler?
create_url_record_on_DB = function(req, res, next) {
dns.lookup(req.body.urlToBeShortened, function(err, addresses) {
if (err) {
return res.json({ error: "invalid url" });
} else {
const URLSPair = new URLShortenerModel({
originalURL: req.body.urlToBeShortened,
});
URLSPair.save(function(err) {
if (err) return console.error(err);
res.json({
original_url: req.body.urlToBeShortened,
short_url: "TO BE IMPLEMENTED",
});
});
}
});
};
And the route
app.post("/api/shorturl/new", create_url_record_on_DB);
Challenge: URL Shortener Microservice
Link to the challenge: