From 9132ae2dea40354e7fa73b5347d2dab30319f93e Mon Sep 17 00:00:00 2001 From: christophhagen Date: Thu, 28 May 2020 12:35:38 +0200 Subject: [PATCH] Correctly index caps --- Sources/App/routes.swift | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/Sources/App/routes.swift b/Sources/App/routes.swift index 042b479..3711aa6 100755 --- a/Sources/App/routes.swift +++ b/Sources/App/routes.swift @@ -64,23 +64,27 @@ public func routes(_ router: Router) throws { // Get the name of a cap router.getCatching("name", Int.parameter) { request -> Data in let cap = try request.parameters.next(Int.self) - guard cap < caps.count else { + let index = cap - 1 + guard index >= 0, index < caps.count else { + log("Trying to get name for invalid cap \(cap) (\(caps.count) caps loaded)") throw CapError.unknownId } - return caps[cap].data(using: .utf8)! + return caps[index].data(using: .utf8)! } // Set the name of a cap router.postCatching("name", Int.parameter) { request in let cap = try request.parameters.next(Int.self) + let index = cap - 1 guard let data = request.http.body.data, let name = String(data: data, encoding: .utf8) else { throw CapError.invalidBody } - guard cap <= caps.count else { + guard index <= caps.count else { + log("Trying to set name for cap \(cap), but only \(caps.count) caps exist") throw CapError.unknownId } - if cap == caps.count { + if index == caps.count { caps.append(name) // Create image folder let url = folder(of: cap) @@ -88,9 +92,10 @@ public func routes(_ router: Router) throws { try fm.createDirectory(at: url, withIntermediateDirectories: false) } } else { - caps[cap] = name + caps[index] = name } try caps.joined(separator: "\n").data(using: .utf8)!.write(to: nameFile) + log("Set name for cap \(cap) (\(caps.count) caps loaded)") } // Upload an image