diff --git a/Sources/App/CapServer.swift b/Sources/App/CapServer.swift index 64698bb..285f66d 100644 --- a/Sources/App/CapServer.swift +++ b/Sources/App/CapServer.swift @@ -86,9 +86,14 @@ final class CapServer { } private func loadCaps() throws { - let data = try Data(contentsOf: dbFile) - caps = try JSONDecoder().decode([Cap].self, from: data) - .reduce(into: [:]) { $0[$1.id] = $1 } + do { + let data = try Data(contentsOf: dbFile) + caps = try JSONDecoder().decode([Cap].self, from: data) + .reduce(into: [:]) { $0[$1.id] = $1 } + } catch { + log("Failed to load caps: \(error)") + throw error + } log("\(caps.count) caps loaded") } @@ -146,10 +151,15 @@ final class CapServer { // MARK: Counts private func updateCounts() throws { - caps = try caps.mapValues { - var cap = $0 - cap.count = try count(of: $0.id) - return cap + do { + caps = try caps.mapValues { + var cap = $0 + cap.count = try count(of: $0.id) + return cap + } + } catch { + log("Failed to update counts: \(error)") + throw error } } diff --git a/Sources/App/configure.swift b/Sources/App/configure.swift index b620b89..51e61b1 100755 --- a/Sources/App/configure.swift +++ b/Sources/App/configure.swift @@ -13,13 +13,9 @@ public func configure(_ app: Application) throws { .appendingPathComponent("config.json") let config: Config if !FileManager.default.fileExists(atPath: configFile.path) { - config = .default - let configData = try JSONEncoder().encode(config) - try configData.write(to: configFile) - print("Wrote default configuration") + config = try writeDefaultCofig(to: configFile) } else { - let configData = try Data(contentsOf: configFile) - config = try JSONDecoder().decode(Config.self, from: configData) + config = try loadConfig(at: configFile) } try Log.set(logFile: config.logPath) @@ -36,3 +32,25 @@ public func configure(_ app: Application) throws { // 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 + } +}