Page Controller

Posted by Dustin Boston .

The Page Controller uses a controller for each logical page on a website. It is responsible for decoding the request URL, extracting form data, creating a model, determining which view to display, and forwarding the model to a view to render the page.

Source Code Listing

code.ts

const artists = [
  {name: "Eminem", genre: "Rap", origin: "Detroit, MI"},
  {name: "Deftones", genre: "Alternative Metal", origin: "Sacramento, CA"},
  {name: "Sublime", genre: "Ska Punk", origin: "Long Beach, CA"},
];

export class Artist {
  static findNamed(name: string | null): Artist | undefined {
    if (!name) return undefined;

    const artist = artists.find(
      (x) => x.name.toLowerCase() === name.toLowerCase(),
    );

    return artist
      ? new Artist(artist.name, artist.genre, artist.origin)
      : undefined;
  }

  constructor(
    public name: string,
    public genre: string,
    public origin: string,
  ) {}
}

export const template = (artist: Artist) => `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>${artist.name}</title>
</head>
<body>
  <h1>${artist.name}</h1>
  <p>Genre: ${artist.genre}</p>
  <p>Origin: ${artist.origin}</p>
</body>
</html>
`;

export class ArtistController {
  static handleRequest(req: Request): Response {
    const url = new URL(req.url);
    const artist = Artist.findNamed(url.searchParams.get("name"));

    if (!artist) {
      return new Response("Artist not found", {status: 404});
    }

    return new Response(template(artist), {
      status: 200,
      headers: {
        "Content-Type": "text/html",
      },
    });
  }
}

Bun.serve({
  routes: {
    "/artist": (req) => {
      return ArtistController.handleRequest(req);
    },
  },
});