I am doing the Back End Development and APIs Projects - URL Shortener Microservice | Learn | freeCodeCamp.org challenge.
Logic- If the given URL previously exists in database, then return its short_url
, else find the last saved short_url
, increase it by 1 and set this number as the short_url
to this URL, save it and send it back to the user.
The problem is my app gives the same short_url
for every URL given. Below is my code,
const urlSchema = new Schema({
original_url: String,
short_url: Number
});
let URLs = mongoose.model("URLs", urlSchema);
app.post("/api/shorturl", function(req, res, next) {
const url = req.body.url.match(/https?:\/\/w{0,3}\.?([^\/]+)\/?.*/)[1];
dns.lookup(url, (err) => {
if (err) {
res.json({ error: 'invalid url' });
return
}
// Check url in database
URLs.findOne({ original_url: req.body.url }, function(err, doc) {
if (err) {
res.send(err);
return
}
// If exists, send that shorturl,
if (doc) {
res.json({ original_url: doc.original_url, short_url: doc.short_url });
return
}
// Else send the Increament of the last short by 1 and store it with this url
next()
})
})
}, function(req, res) {
URLs.findOne().sort({ created_at: -1 }).exec(function(err, doc) {
const newDoc = new URLs({ original_url: req.body.url, short_url: doc ? (doc.short_url + 1) : 1 });
newDoc.save(function(err, data) {
if (err) {
res.send(err);
return
}
res.json({ original_url: data.original_url, short_url: data.short_url })
})
})
});