Macro API

Hey.

I like random-d.uk/api but it's kind of slow, so I decided to rebuild it. Honestly, I just wanted an excuse to try out Hono since I'd just discovered it and needed a small project to mess around with.

After rebuilding it, I thought it'd be cool to have my own collection of random images. I browsed Reddit a bit and found r/macroporn, which has some really nice macro photos.

Macro photography

The project grabs photos I've stored on Cloudflare Images (using Cloudflare KV) and serves them randomly through a simple API. Here's what the code looks like:

import { Hono } from 'hono'

const app = new Hono<{ Bindings: CloudflareBindings }>()
let cache: string[] = []

app.get('/random', async (c) => {
  if (!cache.length) {
    const { keys } = await c.env.KV.list<{ url: string }>()
    cache = keys.map(({ metadata }) => metadata!.url)
  }

  const index = Math.floor(Math.random() * cache.length)
  return c.redirect(cache[index])
})

export default app

Hono is really simple to write, honestly.

Right now I've got a scraper pulling from Reddit, and I'll probably add more photos manually later.