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>
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
import Hummingbird
|
||||
import HummingbirdElementary
|
||||
|
||||
/// Serves the website's root routes.
|
||||
///
|
||||
/// The controller exposes its routes as a `RouteCollection` so they can be added to a router
|
||||
/// (or a sub-group) by the application that composes it:
|
||||
///
|
||||
/// ```swift
|
||||
/// router.addRoutes(RootController<AppRequestContext>().routes)
|
||||
/// ```
|
||||
///
|
||||
/// - 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: RequestContext> : Sendable{
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a root controller.
|
||||
public init() {}
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The routes served by the controller.
|
||||
///
|
||||
/// Serves a `GET` request for the root path (`/`) by rendering the ``IndexPage``.
|
||||
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.
|
||||
/// - Parameters:
|
||||
/// - request: the incoming request.
|
||||
/// - context: the context the request is resolved against.
|
||||
/// - Returns: an HTML response that renders the ``IndexPage``.
|
||||
@Sendable
|
||||
func index(
|
||||
request: Request,
|
||||
context: some RequestContext
|
||||
) -> HTMLResponse {
|
||||
.init {
|
||||
IndexPage()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
extension RouterPath {
|
||||
/// A namespace for the ``RootController`` route paths.
|
||||
enum Root {
|
||||
/// The path of the landing page.
|
||||
static let index: RouterPath = "/"
|
||||
}
|
||||
}
|
||||
@@ -3,16 +3,7 @@ import Configuration
|
||||
extension ConfigValue {
|
||||
/// A namespace for the HTTP server's default configuration values.
|
||||
public enum HTTP {
|
||||
/// The default host the server binds to.
|
||||
public static let host: ConfigValue = .init(stringLiteral: "127.0.0.1")
|
||||
/// The default port the server listens on.
|
||||
public static let port: ConfigValue = .init(stringLiteral: "0")
|
||||
/// The default server name.
|
||||
public static let serverName: ConfigValue = .init(stringLiteral: .Server.name)
|
||||
}
|
||||
/// A namespace for the logging default configuration values.
|
||||
enum Log {
|
||||
/// The default minimum log level.
|
||||
public static let level: ConfigValue = .init(stringLiteral: "trace")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,46 +1,19 @@
|
||||
import Foundation
|
||||
import Elementary
|
||||
import Hummingbird
|
||||
import NIOCore
|
||||
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 preloaded
|
||||
/// error page and a `404 Not Found` status.
|
||||
/// 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: Properties
|
||||
|
||||
/// The body of the error page served on a not-found response.
|
||||
private let page: ByteBuffer
|
||||
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a middleware that serves the error page (`404.html`) from the static files folder.
|
||||
///
|
||||
/// The page is read once, at construction. A minimal fallback body is used when the file is
|
||||
/// missing.
|
||||
/// - Parameter staticFilesPath: the folder, relative to the working directory, the static files are served from.
|
||||
public init(
|
||||
_ staticFilesPath: String
|
||||
) {
|
||||
let path = StaticFile.errorHTML.path(relativeTo: staticFilesPath)
|
||||
|
||||
if let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
|
||||
self.init(page: .init(bytes: data))
|
||||
} else {
|
||||
self.init(page: .init(string: "404 Not Found"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a middleware that serves the given error page on a not-found response.
|
||||
/// - Parameter page: the body of the error page.
|
||||
init(
|
||||
page: ByteBuffer
|
||||
) {
|
||||
self.page = page
|
||||
}
|
||||
|
||||
|
||||
/// Creates a not-found middleware.
|
||||
public init() {}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - RouterMiddleware
|
||||
@@ -49,6 +22,16 @@ 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,
|
||||
@@ -57,7 +40,6 @@ extension NotFoundMiddleware: RouterMiddleware {
|
||||
do {
|
||||
return try await next(request, context)
|
||||
} catch let error {
|
||||
// Only intercept "not found"; let every other error propagate.
|
||||
guard
|
||||
let responseError = error as? any HTTPResponseError,
|
||||
responseError.status == .notFound
|
||||
@@ -65,14 +47,14 @@ extension NotFoundMiddleware: RouterMiddleware {
|
||||
throw error
|
||||
}
|
||||
|
||||
var headers = HTTPFields()
|
||||
|
||||
headers[.contentType] = StaticFile.errorHTML.contentType
|
||||
|
||||
return Response(
|
||||
status: .notFound,
|
||||
headers: headers,
|
||||
body: .init(byteBuffer: page)
|
||||
return HTMLResponse(
|
||||
status: .notFound
|
||||
) {
|
||||
ErrorPage()
|
||||
}
|
||||
.response(
|
||||
from: request,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user