Humbly: my first worker. Using kv to serve images by name

This is just a little extension of this code by @Walshy.

A call for https://yourworkerdomain/variant/imagename.jpg
will bring up the image if there is a kv entry with imagename/imageid

I added:

  • reverse image and variant, so the variant looks like a folder.
  • look for the file name in a KV set, and pull the image id if found

Still to do:

  • default variant if not specified
  • handle errors, key not found, etc (maybe serve a default image )
  • another worker that periodically pulls the full list of images by the image API, and uploads it to the KV space by the KV API. This may get hairy once the images list gets paginated.
  • an API point that handles image uploading, if provided with an image url.

Hopefully later:

  • if the LIST call of the images API is amended to display metadata (it doesn’t now), it could also be saved in KV, and then be used to tie images to products or postings. This way images can be called by usage “main-image-product-123” and both image ids and names become irrelevant.
addEventListener('fetch', (event) => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const accountHash = 'yourhash';
  const domain = 'https://imagedelivery.net/';
  const url = new URL(request.url);
  let { pathname } = url;
  const arr = pathname.split("/");
  const id = await images.get(arr[2]);
  const out = domain+accountHash+'/'+id+'/'+arr[1];

return fetch(out);
}
1 Like