URL Shortener on Cloudflare Workers with Visit Count
Thanks to https://github.com/EasyChris/Url-Shorten-Worker for implementing the basic counting functionality.
Building on this, I further optimized the operation page so that you can read the visit count directly on the operation page, without needing to check the visit count in the KV backend.
Demo
Brief description of @EasyChris's solution
Create a record of shortlink-count in KV, storing the number of visits.
For example: if the short link is NEhFs7, then the count record is NEhFs7-count
I'm not the author of this part, so I won't go into detail.
My further optimization process
index.js
Optimized the code, moving the password check out of each command's branch to the outermost level.
Added the
qry command, which can query KV.I use it here to query the count value, but it can actually also be used to query the long link corresponding to a short link. In other words, it can serve as a standalone short link API with add, delete, and query capabilities.
main.js
The actual action of the query count button
========
Postscript
When the counting feature is enabled, the number of writes to KV increases significantly. When creating a short link, it originally only wrote once, but now it needs to write twice; when querying, it used to just read, but now it also needs to write once.
Setting the visit_count config option to true enables the counting feature. The default in the configuration file on Github is disabled.
Github: https://github.com/crazypeace/Url-Shorten-Worker