Hey @rudolphh, yep I think I must have sunk just about a day on wrapping my head around the best way to generate an unique short identifier to act as the short_url. I similarly ended up opting for an auto incrementing number, which took quite a bit of time to get up and running.
I think you’re right, it’s probably not the best solution, but my frame of mind was to avoid using too much abstraction (because, “All magic comes at a price!”).
In anycase, here is the piece of my code that handles that:
// Saves a new URL to the database returning the new extension on this domain (shortened URL)
function saveURL(url, callback) {
getNextSequence('urlid', function(err, seq) {
if (err) console.error(err);
var newUrl = {
"original_url": url,
"short_url": DOMAIN + '/' + seq
};
db.collection(DB_COLLECTION_NAME).insert(newUrl, function(err, result) {
if (err) console.error(err);
callback(newUrl);
});
});
}
function getNextSequence(name, callback){
db.collection("counters").findAndModify(
{ "_id": name },
[],
{ "$inc": { "seq": 1 }},
{ "new": true, "upsert": true },
function(err, result) {
callback( err, result.value.seq );
}
);
}
I mean to comment this in the near future (ideally today), but to fill you in in the mean time.
getNextSequence() looks into a separate collection called ‘counters’ which I have manually initialised with the following document:
{
"_id": "urlid",
"seq": 0
}
Every time getNextSequence() is called is called it will increment and update the ‘seq’ (sequence) value and return it to its callback.
It’s callback in this case is more or less the meat of my saveURL() function, which is executed whenever a user requests to add a new url. I enter the code block that saves the new URL in my database. It needs to be within the callback of getNextSequence() because it requires that new sequence numbers, it is the short URL extension associated with that new URL.
You can see why this is a performance issue, the saving of new URLs to the database becomes dependant on writing and receiving the new updated sequence number before doing so. If you were doing this at scale I imagine it would be a nightmare!
Hope this makes sense. Godspeed Rudus!
Allan