Files
ccn/Services/Website/Sources/App/App+build.swift
T

92 lines
2.6 KiB
Swift
Raw Normal View History

2026-06-27 02:26:33 +00:00
import Configuration
import Hummingbird
import Logging
import WebsiteCore
2026-06-27 02:26:33 +00:00
/// Builds the website application.
///
/// Reads the log level, server name, and static files location from the configuration,
/// then assembles the router, server configuration, and logger.
/// - Parameter reader: the configuration reader the values are read from.
/// - Returns: the configured application, ready to run as a service.
/// - Throws: an error if the router fails to build.
2026-06-27 02:26:33 +00:00
func application(
reader: ConfigReader
) async throws -> some ApplicationProtocol {
let logLevel = reader.string(
forKey: .Log.level,
2026-06-27 02:26:33 +00:00
as: Logger.Level.self,
default: .info
)
let serverName = reader.string(
forKey: .HTTP.serverName,
default: .Server.name
)
let staticFilesPath = reader.string(
forKey: .Path.staticFiles,
default: .Path.staticResources
2026-06-27 02:26:33 +00:00
)
return Application(
router: router(
staticFilesPath: staticFilesPath,
logLevel: logLevel
),
2026-06-27 02:26:33 +00:00
configuration: ApplicationConfiguration(
reader: reader.scoped(to: "http")
),
logger: logger(
serverName: serverName,
logLevel: logLevel
)
)
}
// MARK: - Helpers
// Request context used by application
private typealias AppRequestContext = BasicRequestContext
/// Builds the application's logger.
/// - Parameters:
/// - serverName: the label applied to the logger.
/// - logLevel: the minimum level the logger emits.
/// - Returns: the configured logger.
2026-06-27 02:26:33 +00:00
private func logger(
serverName: String,
logLevel: Logger.Level
) -> Logger {
var logger = Logger(label: serverName)
logger.logLevel = logLevel
return logger
}
/// Builds the application's router.
///
/// Registers, in order, the request-logging middleware, the not-found middleware that serves
/// the error page, and the static file middleware that serves the contents of `staticFilesPath`
/// (falling back to `index.html` for directory requests).
/// - Parameters:
/// - staticFilesPath: the folder, relative to the working directory, the static files are served from.
/// - logLevel: the level the request-logging middleware logs at.
/// - Returns: the configured router.
private func router(
staticFilesPath: String,
logLevel: Logger.Level
) -> Router<AppRequestContext> {
2026-06-27 02:26:33 +00:00
let router = Router(context: AppRequestContext.self)
router.addMiddleware {
LogRequestsMiddleware(logLevel)
NotFoundMiddleware(staticFilesPath)
FileMiddleware(
staticFilesPath,
searchForIndexHtml: true
)
2026-06-27 02:26:33 +00:00
}
return router
}