Files
ccn/Services/Website/Sources/Library/Public/Middlewares/NotFoundMiddleware.swift
T
javier a621ada0bf HTML rendering support for the Website service (#5)
This PR contains the work done to replace the use of static _HTML_ files with type-safe HTML rendered server-side via **Elementary** through **Hummingbird**.

To provide further details about the work done:

* Added the **Elementary** dependencies.
* Added the `IndexPage` and `ErrorPage` pages, ported from the old HTML boilerplate; removed the static files.
* Added the `RootController` controller serving GET / using the `IndexPage` page, wired into the router.
* Reworked the `NotFoundMiddleware` middleare to render `ErrorPage` page directly; non-notFound errors still propagate.
* the `FileMiddleware` middleware no longer searches for any static `index.html` file.
* Simplified the `StaticFile` enumeration, dropped unused constants and now-unnecessary throws.

Reviewed-on: rock-n-code/loud-amsterdam#5
Co-authored-by: Javier Cicchelli <javier@rock-n-code.com>
Co-committed-by: Javier Cicchelli <javier@rock-n-code.com>
2026-06-28 05:07:19 +00:00

63 lines
1.9 KiB
Swift

import Elementary
import Hummingbird
import HummingbirdElementary
/// Serves a custom error page for requests that match neither a route nor a static file.
///
/// Placed ahead of `FileMiddleware` in the middleware chain, it catches the `.notFound` error
/// that bubbles up when no file exists for the requested path and responds with the rendered
/// ``ErrorPage`` and a `404 Not Found` status.
public struct NotFoundMiddleware<Context: RequestContext> {
// MARK: Initializers
/// Creates a not-found middleware.
public init() {}
}
// MARK: - RouterMiddleware
extension NotFoundMiddleware: RouterMiddleware {
// MARK: Functions
/// Passes the request down the chain, rendering the error page if it results in a not-found
/// response.
///
/// Any error other than `.notFound` is rethrown unchanged.
/// - Parameters:
/// - request: the incoming request.
/// - context: the context the request is resolved against.
/// - next: the next responder in the middleware chain.
/// - Returns: the downstream response, or the rendered ``ErrorPage`` with a `404 Not Found` status.
/// - Throws: any non-not-found error thrown downstream.
public func handle(
_ request: Request,
context: Context,
next: (Request, Context) async throws -> Response
) async throws -> Response {
do {
return try await next(request, context)
} catch let error {
guard
let responseError = error as? any HTTPResponseError,
responseError.status == .notFound
else {
throw error
}
return HTMLResponse(
status: .notFound
) {
ErrorPage()
}
.response(
from: request,
context: context
)
}
}
}