From 6e5cc06d31ac7a401d7685a38f13cb311e21535b Mon Sep 17 00:00:00 2001 From: Christoph Hagen Date: Sun, 12 Mar 2023 11:49:33 +0100 Subject: [PATCH] Return updated cap when deleting image --- Sources/App/CapServer+Routes.swift | 5 ++++- Sources/App/CapServer.swift | 21 +++++++++++++++++---- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/Sources/App/CapServer+Routes.swift b/Sources/App/CapServer+Routes.swift index 6b34940..445a2a2 100755 --- a/Sources/App/CapServer+Routes.swift +++ b/Sources/App/CapServer+Routes.swift @@ -4,6 +4,8 @@ import Foundation /// The decoder to extract caps from JSON payloads given to the `cap` route. private let decoder = JSONDecoder() +private let encoder = JSONEncoder() + /// The date formatter to decode dates in requests private let dateFormatter: DateFormatter = { let df = DateFormatter() @@ -113,9 +115,10 @@ extension CapServer { try self.ensureOperability() 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) } + return try encoder.encode(cap) } } } diff --git a/Sources/App/CapServer.swift b/Sources/App/CapServer.swift index d292fde..d98e4c3 100644 --- a/Sources/App/CapServer.swift +++ b/Sources/App/CapServer.swift @@ -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) { var cap = cap let folderUrl = folder(of: cap.id) @@ -268,7 +274,14 @@ final class CapServer { } sorted.insert((version, newUrl), at: version) } + cap.count = sorted.count + + // Fix invalid main image + if cap.mainImage >= cap.count || cap.mainImage < 0 { + cap.mainImage = 0 + } + caps[cap.id] = cap } @@ -478,18 +491,18 @@ final class CapServer { 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 { log("Attempting to delete image \(version) of unknown cap \(capId)") - return false + return nil } let capImageUrl = imageUrl(of: capId, version: version) guard exists(capImageUrl) else { log("Attempting to delete missing image \(version) of cap \(capId)") - return false + return nil } organizeImages(for: cap) - return true + return caps[capId]! } // MARK: Classifier