From e49cc9cb91a7bbe74d95b0502e7aaf809137ac77 Mon Sep 17 00:00:00 2001 From: Christoph Hagen Date: Tue, 11 Oct 2022 12:00:46 +0200 Subject: [PATCH] Load configuration from file --- Sources/App/Management/Configuration.swift | 32 ++++++++++++++++++++++ Sources/App/configure.swift | 6 +++- 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 Sources/App/Management/Configuration.swift diff --git a/Sources/App/Management/Configuration.swift b/Sources/App/Management/Configuration.swift new file mode 100644 index 0000000..57796e9 --- /dev/null +++ b/Sources/App/Management/Configuration.swift @@ -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 { + +} diff --git a/Sources/App/configure.swift b/Sources/App/configure.swift index c8de8af..085afca 100644 --- a/Sources/App/configure.swift +++ b/Sources/App/configure.swift @@ -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