Cloudflare Worker Short URL: Query All Links Feature

Requirement

Diet & Health, January 2, 2024, GMT+8 03:52:00
Hope you can add a feature to query previously added short links from Cloudflare. Otherwise, if the browser cache is wiped, or when I want to query and manage short links on another computer, I have to log into Cloudflare, which is quite troublesome.


When I first designed this short link system, I intended it to be shared among people I know. That's why I used the browser's localStorage — the benefit is that each person only sees the short links they added themselves, without interfering with each other. Later I added a delete feature, so you won't accidentally delete someone else's short links either.

However, since someone specifically asked for it, let me think again — if this system is only used by myself, then the need to read KV is reasonable.


Approach

Refer to the official documentation https://developers.cloudflare.com/kv/api/list-keys/

list() can return the full list of keys (i.e., short links). Then query each one separately to get the value (i.e., the long link), and stitch them together into a JSON structure to return to the front-end page.


Design the Data Structure

The JSON structure sent from the front-end to the back-end, design a command qryall

{
  cmd: 'qryall', 
  password: 'bodongshouqulveweifengci'
}

The JSON structure returned from the back-end to the front-end

{
  "status":200,
  "error":"",
  "kvlist":[
    {
      "key":"mtSzm6",
      "value":"https://1way.eu.org/bodongshouqulveweifengci"
    },
    .... etc ...
  ]
}


Write the Code

Add a loadKV() function to main.js used by the front-end page

loadKV function using qryall query and writing the result to localStorage

Add a button on the front-end page index.html to call loadKV()

Short URL management interface, red box arrow pointing to load KV to localStorage button

The back-end implementation worker.js adds handling for the qryall command

Code showing qryall calling LINKS.list() to iterate over keys and values and return JSON


========

The End

Github: https://github.com/crazypeace/Url-Shorten-Worker

Added a switch, off by default. 

load_kv set to false in worker.js, marked with a red box

The demo site has this feature enabled. https://1way.eu.org/mtSzm6

* It's not ruled out that in the future, due to conflicts between features (or impacts on the effect), the demo site may disable this feature.


========

update

Important reminder! list() is limited to only 1000 free calls per day

Workers KV pricing table with red box marking the free plan's 1000 List requests per day


Comments