The Front Controller is a design pattern that processes all requests to a
website using a single handler. The handler decodes the URL and extracts request
data to determine which command should process the request. This pattern pairs
well with the Intercepting Filter (Decorator) pattern.
Fowler, M. (2011). Patterns of Enterprise Application Architecture.
Addison-Wesley.
exportabstractclassFrontCommand{protectedrequest: Request;constructor(request: Request){this.request=request;}abstractprocess():Promise<Response>;/**
* Helper to build a response by forwarding to a static file (the "view").
*/protectedasyncforward(pathname: string):Promise<Response>{// Use Bun.file for optimized file serving.
constfile=Bun.file(`${import.meta.dir}/../${pathname}`);if(awaitfile.exists()){returnnewResponse(file);}returnnewResponse("Not Found",{status: 404});}}exportclassArtistCommandextendsFrontCommand{asyncprocess():Promise<Response>{consturl=newURL(this.request.url);constartistName=url.searchParams.get("name");console.log(`Fetching data for artist: ${artistName}`);// The path is relative to the project root.
returnthis.forward("views/artist.html");}}exportclassUnknownCommandextendsFrontCommand{asyncprocess():Promise<Response>{returnnewResponse("Command not found.",{status: 404});}}typeCommandConstructor=new(request: Request)=>FrontCommand;exportclassFrontController{publicasynchandle(request: Request):Promise<Response>{constCommand=awaitthis.getCommandClass(request);constcommandInstance=newCommand(request);returncommandInstance.process();}privateasyncgetCommandClass(request: Request):Promise<CommandConstructor>{consturl=newURL(request.url);constcommandName=url.searchParams.get("command");switch(commandName?.toLowerCase()){case"artist":returnArtistCommand;default:returnUnknownCommand;}}}constcontroller=newFrontController();constport=3000;Bun.serve({port,fetch:(request)=>controller.handle(request)});console.log(`Server running with Bun at http://localhost:${port}`);