Correctly index caps

This commit is contained in:
christophhagen 2020-05-28 12:35:38 +02:00
parent d7f875cf88
commit 9132ae2dea

View File

@ -64,23 +64,27 @@ public func routes(_ router: Router) throws {
// Get the name of a cap // Get the name of a cap
router.getCatching("name", Int.parameter) { request -> Data in router.getCatching("name", Int.parameter) { request -> Data in
let cap = try request.parameters.next(Int.self) 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 throw CapError.unknownId
} }
return caps[cap].data(using: .utf8)! return caps[index].data(using: .utf8)!
} }
// Set the name of a cap // Set the name of a cap
router.postCatching("name", Int.parameter) { request in router.postCatching("name", Int.parameter) { request in
let cap = try request.parameters.next(Int.self) 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 { guard let data = request.http.body.data, let name = String(data: data, encoding: .utf8) else {
throw CapError.invalidBody 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 throw CapError.unknownId
} }
if cap == caps.count { if index == caps.count {
caps.append(name) caps.append(name)
// Create image folder // Create image folder
let url = folder(of: cap) let url = folder(of: cap)
@ -88,9 +92,10 @@ public func routes(_ router: Router) throws {
try fm.createDirectory(at: url, withIntermediateDirectories: false) try fm.createDirectory(at: url, withIntermediateDirectories: false)
} }
} else { } else {
caps[cap] = name caps[index] = name
} }
try caps.joined(separator: "\n").data(using: .utf8)!.write(to: nameFile) try caps.joined(separator: "\n").data(using: .utf8)!.write(to: nameFile)
log("Set name for cap \(cap) (\(caps.count) caps loaded)")
} }
// Upload an image // Upload an image