Ouch! I decided to refactor it using Hono, a modern web framework built for the edge that has excellent TypeScript support, uses Web Standard APIs, and can deploy to Cloudflare Workers (among many other providers) out-of-the-box, lending itself to being an elegant and standardized choice.
The first thing to do was to place the list of HTTP status codes into a separate file, so I stored them in an array (of tuples) which ensured it was safely typed and easily importable into the index.ts entrypoint:
The key to this entire project is the actual status code, so being able to lookup the code quickly and accurately is important. An array isn’t an ideal data structure to achieve this, therefore using a Map is better since the keys can be numbers, and lookups are very performant:
TypeScript will infer the type from the Map keyword, but I like explicitly setting the type as a Map of tuples just to be thorough.
Hono offers an extensive but simple API when responding to GET requests from the Context object. The structure should be idiomatic and easy to understand, but you can read more about it in the docs: hono.dev/api/context#set-get
Hono ingests the code URL parameter as a string, but I needed to parse this as an integer to be able to lookup the Map keys (which themselves are numbers):
I used a number | any type union because TypeScript shows an error when returning just a number type in the Response object due to overloads. There’s most likely a proper a fix for this but laziness took over so here we are.
The actual logic then involves looking up the (parsed) URL parameter to see if a corresponding Map key exists, returning the value of that key as the actual HTTP response code, and also interpolating both the key and value as a text/plain response to be as helpful as possible:
c.header is simply Hono’s method for adding headers to the Context object, which handles Request and Response. While I added statusCode to the return statement for brevity, it could also have been set via c.status(statusCode)
If the Map key doesn’t exist, then the URL parameter isn’t a valid status code, so regardless of the query the result should be a 302 redirect to the project’s about page:
Similarly, any requests to the naked domain should result in a 301 permanent redirect to the project’s about page:
In both cases, Hono’s simplicity allows for creating an inline redirect using the c.redirect() Context method (with the 302 or 301 redirect codes passed as parameters).