I’m trying to make ‘URL Shortener’, and I’m wondering if the short URL have to be a value from an internal counter or can it be anything else? Because I have been trying to make a counter and put the count value as the short url, but I’m struggling making it work.
//create counter schema
const CounterSchema = new mongoose.Schema({
_id: { type: String, require: true },
sequence: { type: Number, require: true}
});
var counter = mongoose.model('counter', CounterSchema);
//create url schema
const UrlSchema = new mongoose.Schema({
original_url: { type: String, require: true},
count: { type: Number, require: false}
});
UrlSchema.pre('save', function(next) {
var doc = this;
counter.findOneAndUpdate(
{_id: 'original_url'},
{ $inc: {sequence: 1} },
{ new: true },
function(err, count) {
if(err) return next(err);
doc.count = count.sequence;
next();
}
);
});
var URL = mongoose.model('URL', UrlSchema);
// your first API endpoint...
app.get("/api/shorturl/:code", function(req, res) {
const urlCode = req.params.code;
URL.findOne({ short_url: urlCode}, function(err, doc) {
if(err) { return console.error(err) };
res.redirect(doc.original_url);
});
});
app.post("/api/shorturl/new", function (req, res) {
const originalUrl = req.body.url;
const host = originalUrl.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0]; //(change from url to host name)
//validate url, dns lookup
dns.lookup(host, function(err) {
if(err) {
res.json({error: 'invalid URL'});
}
else {
//findOne url
URL.findOne({original_url: originalUrl}, function(err, url) {
if(err) { return console.error(err) };
//if url exists in db show json
if(url) {
res.send(url)
}
//if url does not exists in db, save data to server
else {
const url = new URL({ original_url: originalUrl});
url.save();
res.send({ original_url: originalUrl })
}
});
}
});
});