Load configuration from file

This commit is contained in:
Christoph Hagen 2022-10-11 12:00:46 +02:00
parent b7ce607c8b
commit e49cc9cb91
2 changed files with 37 additions and 1 deletions

View File

@ -0,0 +1,32 @@
import Foundation
struct Configuration {
let serverPort: Int
}
extension Configuration {
init(loadFromUrl url: URL) throws {
let data: Data
do {
data = try Data(contentsOf: url)
} catch {
print("Failed to load configuration data from \(url.path): \(error)")
throw error
}
try self.init(data: data)
}
init(data: Data) throws {
do {
self = try JSONDecoder().decode(Configuration.self, from: data)
} catch {
print("Failed to decode configuration: \(error)")
throw error
}
}
}
extension Configuration: Codable {
}

View File

@ -7,7 +7,11 @@ var server: SQLiteDatabase!
public func configure(_ app: Application) throws {
let storageFolder = URL(fileURLWithPath: app.directory.resourcesDirectory)
app.http.server.configuration.port = 6002
let configPath = URL(fileURLWithPath: app.directory.resourcesDirectory)
.appendingPathComponent("config.json")
let configuration = try Configuration(loadFromUrl: configPath)
app.http.server.configuration.port = configuration.serverPort
// Set target environment
app.environment = .production