Return updated cap when deleting image

This commit is contained in:
Christoph Hagen 2023-03-12 11:49:33 +01:00
parent e767957e64
commit 6e5cc06d31
2 changed files with 21 additions and 5 deletions

View File

@ -4,6 +4,8 @@ import Foundation
/// The decoder to extract caps from JSON payloads given to the `cap` route. /// The decoder to extract caps from JSON payloads given to the `cap` route.
private let decoder = JSONDecoder() private let decoder = JSONDecoder()
private let encoder = JSONEncoder()
/// The date formatter to decode dates in requests /// The date formatter to decode dates in requests
private let dateFormatter: DateFormatter = { private let dateFormatter: DateFormatter = {
let df = DateFormatter() let df = DateFormatter()
@ -113,9 +115,10 @@ extension CapServer {
try self.ensureOperability() try self.ensureOperability()
try authenticator.authorize(request) try authenticator.authorize(request)
guard self.deleteImage(version: version, for: cap) else { guard let cap = self.deleteImage(version: version, for: cap) else {
throw Abort(.gone) throw Abort(.gone)
} }
return try encoder.encode(cap)
} }
} }
} }

View File

@ -221,6 +221,12 @@ final class CapServer {
} }
} }
/**
Rearrange images of a cap to ensure that an image exists for each number from 0 to `image count - 1`.
This is done by using the last images to fill in possible gaps in the sequence.
E.g. If there are images `0`, `2`, `3`, then `3` will be renamed to `1`.
- Note: The main image is also changed, if the main image is renamed.
*/
private func organizeImages(for cap: Cap) { private func organizeImages(for cap: Cap) {
var cap = cap var cap = cap
let folderUrl = folder(of: cap.id) let folderUrl = folder(of: cap.id)
@ -268,7 +274,14 @@ final class CapServer {
} }
sorted.insert((version, newUrl), at: version) sorted.insert((version, newUrl), at: version)
} }
cap.count = sorted.count cap.count = sorted.count
// Fix invalid main image
if cap.mainImage >= cap.count || cap.mainImage < 0 {
cap.mainImage = 0
}
caps[cap.id] = cap caps[cap.id] = cap
} }
@ -478,18 +491,18 @@ final class CapServer {
log("Updated cap \(existingCap.id)") log("Updated cap \(existingCap.id)")
} }
func deleteImage(version: Int, for capId: Int) -> Bool { func deleteImage(version: Int, for capId: Int) -> Cap? {
guard let cap = caps[capId] else { guard let cap = caps[capId] else {
log("Attempting to delete image \(version) of unknown cap \(capId)") log("Attempting to delete image \(version) of unknown cap \(capId)")
return false return nil
} }
let capImageUrl = imageUrl(of: capId, version: version) let capImageUrl = imageUrl(of: capId, version: version)
guard exists(capImageUrl) else { guard exists(capImageUrl) else {
log("Attempting to delete missing image \(version) of cap \(capId)") log("Attempting to delete missing image \(version) of cap \(capId)")
return false return nil
} }
organizeImages(for: cap) organizeImages(for: cap)
return true return caps[capId]!
} }
// MARK: Classifier // MARK: Classifier