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
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