Hi all!
Here I’ve used the ObjectId of the URL stored in MongoDB as the shortened URL. This works fine for me. OPEN FOR REVIEWS.
//DB-SCHEMA
var Schema = mongoose.Schema;
var urlShortnerSchema = new Schema({
url: String
});
var urlShortner = mongoose.model("urlShortner", urlShortnerSchema);
//Function to extract domain name from URL
//This is because I use dns.resolve()
let urlExtractor = function(url) {
var urlSplit = url.split("https://");
if (urlSplit[1] == undefined) {
return urlSplit[0].split("/")[0];
} else {
return urlSplit[1].split("/")[0];
}
};
//Input
app.post("/api/shorturl/new", function(req, res) {
var url = req.body.url;
var extractedUrl = urlExtractor(req.body.url);
dns.resolveAny(extractedUrl, (err, address) => {
if (err) {
console.log(err, address);
res.json({ error: "invalid URL" });
} else {
var urlRecord = new urlShortner({ url: url });
urlRecord.save((err, data) => {
if (err) res.json({ error: "invalid URL" });
else {
res.json({ original_url: url, short_url: data._id.toString() });
}
});
}
});
});
//Output-Redirect
app.get("/api/shorturl/:shorturl", function(req, res) {
let shorturl = req.params.shorturl;
let urlId;
try {
urlId = mongoose.Types.ObjectId(shorturl);
} catch (err) {
res.json({ error: "invalid URL" });
console.log("error" + urlId);
}
let completeurl = urlShortner.findById(urlId, (err, data) => {
if (err) {
res.json({ error: "invalid URL" });
console.log("error" + urlId);
} else {
res.status(301).redirect(data.url);
console.log("Success" + urlId);
}
});
});
Code link : https://glitch.com/~thinkable-woolly-money
Live App : https://thinkable-woolly-money.glitch.me