This PR contains the work done to define a `Page` protocol that extracts the HTML scaffolding that `IndexPage` and `ErrorPage` pages duplicated, so every page of the website declares only what makes it unique — its content, title, and assets — while the document structure lives in one place. Also cleans up imports across the workspace. Reviewed-on: rock-n-code/loud-amsterdam#22 Co-authored-by: Javier Cicchelli <javier@rock-n-code.com> Co-committed-by: Javier Cicchelli <javier@rock-n-code.com>
87 lines
2.0 KiB
Swift
87 lines
2.0 KiB
Swift
import Hummingbird
|
|
import Web
|
|
|
|
/// Serves the website's root routes.
|
|
///
|
|
/// The controller exposes its routes through its `RouterController` conformance, so the
|
|
/// application that composes it registers them declaratively:
|
|
///
|
|
/// ```swift
|
|
/// router.addController {
|
|
/// RootController<AppRequestContext>()
|
|
/// }
|
|
/// ```
|
|
///
|
|
/// - Note: `Context` is the request context the routes are resolved against, and must match the
|
|
/// context of the router the routes are added to.
|
|
public struct RootController<Context: LocalizedRequestContext> {
|
|
|
|
// MARK: Properties
|
|
|
|
/// The landing page, rendered once per supported language and reused for every request.
|
|
private let responses: LocalizedHTMLCollectionResponse
|
|
|
|
// MARK: Initializers
|
|
|
|
/// Creates a root controller.
|
|
public init() {
|
|
self.responses = .init {
|
|
IndexPage(locale: $0)
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
// MARK: - RouteController
|
|
|
|
extension RootController: RouterController {
|
|
|
|
// MARK: Properties
|
|
|
|
public var routes: RouteCollection<Context> {
|
|
let routes = RouteCollection(context: Context.self)
|
|
|
|
routes.get(
|
|
.Root.index,
|
|
use: index
|
|
)
|
|
|
|
return routes
|
|
}
|
|
|
|
}
|
|
|
|
// MARK: - Helpers
|
|
|
|
private extension RootController {
|
|
|
|
// MARK: Methods
|
|
|
|
/// Handles a request for the landing page.
|
|
///
|
|
/// Renders the ``IndexPage`` in the language stored on the context by ``LocalizationMiddleware``,
|
|
/// falling back to the default language.
|
|
/// - Parameters:
|
|
/// - request: the incoming request.
|
|
/// - context: the context the request is resolved against.
|
|
/// - Returns: the cached ``IndexPage`` response for the context's language.
|
|
@Sendable
|
|
func index(
|
|
request: Request,
|
|
context: Context
|
|
) -> Response {
|
|
responses.response(for: context.language)
|
|
}
|
|
|
|
}
|
|
|
|
// MARK: - Constants
|
|
|
|
private extension RouterPath {
|
|
/// A namespace for the ``RootController`` route paths.
|
|
enum Root {
|
|
/// The path of the landing page.
|
|
static let index: RouterPath = "/"
|
|
}
|
|
}
|