Yes this is a funny challenge. When I got to programming I did Ruby on Rails. Why ? Cause I follow a guys on youtube call Mackenzie Child. He did this channel for learning RoR. The playlist here
So yes I try to make like him, not really for learning but more for push myself. I always want to build something but I never push myself til the end. So this is the opportunity for me to make little app and get stuff to show for portfolio.
So for the first week, the app I choice was a simple shortened URL. The stack is with
jQuery. Nothing too hard so no need to add
React on this stack.
If we take the app in part I need to:
- Get URL from the user
- Make a random smaller URL with an algorithm and be sure this is unique.
- Give back to the use the short URL version
- Make a route who handle the short URL as a params and redirect the user to this real link.
I don’t say I have the best strategies here. I just show you what I did and that work :)
So here nothing really amazing. You can see I have put the shortUrl to be maximum 6 character length. The only thing you need to know if the shortUrl gonna be the params now and we redirect the user to the longUrl version who is the real one.
Now time to work on the algorithm. I use the
[crypto](https://nodejs.org/api/crypto.html) module who is a node api.
Nothing awesome, just a good plain base64 random string. The
len arguments gonna 6 for my case.
So I use the
pre save method of mongoose and make it build the shortUrl. You can see I make a findOne too for looking if that exist. If yes I rerun it for be sure this is unique. About the addHtpp function who is:
This is for adding
http in front of longUrl. Cause I was getting problem with express for redirect user without. I got the redirect always on my domains and this is the hack I found.
Nothing magic again here, the only weird thing is the fact than I reuse the addHtpp function. Because I put in the db the one with http I need to match it cause when I user create a shortUrl example with
www.facebook.com I need to see if the http version is already there.
For the redirectLong action I just push the user with the longUrl coming from the Url find by the params in the url.
All the other code is more design, jQuery etc. Nothing is brand new and surely not the best jQuery code. I didn’t touch it for like 6 months.
Hope this blog post help you to see the logic about making this kind of app. I talk here for the beginner one or the one who didn’t really think about make this. Let me know in the comment if you have any suggestions.
You can see the app here and play around with.
The code is here on github.