If you look at the bottom of this page, you’ll see a button that says something along the lines of “x people have liked this page”. Go ahead, click it and watch what happens!
This button calls a tiny Mojolicious microservice that I have created thats sole purpose is to keep track of how many people like the post. I’m going to quickly give an overview about how it works!
Mojolicious is a web application framework written in Perl. It is fantastic for building web applications of any size. I’m going to dive into the code that makes this whole process work. Before I begin, let me just be clear that ‘star’ and ‘like’ are synonymous with each other.
Each post on my website has a
star_id associated with it. This is simply a unique ID that is associated with each post. It is generated from Online UUID Generator. After clicking the button under the post, a request is sent to the microservice to increment the ‘star’ count. This is done by inserting a record into a SQLite database. In order to ensure that people can only like the post once, the IP address of the user who liked the content is taken into account. Don’t worry, your IP address is not stored in the database. Only the MD5 hash of it is.
As you can see, the
stars table is very simple. It stores the star_id and the MD5 hash of the users IP address. There is a UNIQUE constraint on the table which ensures that each
ip_address combination is unique.
This application only has two endpoints. One to increment the ‘star’ count (also known as the ‘like’ count) for each post, and one to simply view the number of likes. Mojolicious is known for its amazing websocket support, however I opted to using simple HTTP routes to limit the complexity of the application.
To get the current ‘like’ count for the post, we just need to get the number of rows in the
stars table that match the passed in
To increment the ‘like’ count we just insert the request into the database, and let SQLite determine if this is a duplicate request.
Hooking it Up
Now that the backend is complete, we just have to tell the button on the page to call the appropriate routes. The entire front-end code is only ~40 lines long. Here it is!
This will display the button with the correct ‘like’ count, and it will increment the count when clicked. Additionally, the ‘like’ count is fetched every 10 seconds to get an accurate count without having to refresh the page.
That’s pretty much it. If you would like to see the full source code, please click here!