Caps-Server/Sources/App/configure.swift
2023-01-11 18:26:53 +01:00

47 lines
1.3 KiB
Swift
Executable File

import Vapor
import Foundation
private(set) var server: CapServer!
public func configure(_ app: Application) throws {
try Log.set(logFile: config.logPath)
let resourceDirectory = URL(fileURLWithPath: app.directory.resourcesDirectory)
let publicDirectory = app.directory.publicDirectory
let config = Config(loadFrom: resourceDirectory)
if config.serveFiles {
let middleware = FileMiddleware(publicDirectory: publicDirectory)
app.middleware.use(middleware)
}
server = try CapServer(in: URL(fileURLWithPath: publicDirectory),
writers: config.writers)
// Register routes to the router
try routes(app)
}
private func writeDefaultCofig(to path: URL) throws -> Config {
do {
let configData = try JSONEncoder().encode(Config.default)
try configData.write(to: path)
print("Wrote default configuration to \(path.path)")
return .default
} catch {
print("Failed to write default config file at \(path.path): \(error)")
throw error
}
}
private func loadConfig(at path: URL) throws -> Config {
do {
let configData = try Data(contentsOf: path)
return try JSONDecoder().decode(Config.self, from: configData)
} catch {
print("Failed to load config file at \(path.path): \(error)")
throw error
}
}