From 208737414ab7577cb7772d81055c84f8d8619caf Mon Sep 17 00:00:00 2001 From: "Steffen D. Sommer" Date: Mon, 16 Jul 2018 10:55:52 +0200 Subject: [PATCH] Add support for restoring deleted entities --- Sources/Sugar/Entity+Sugar.swift | 54 ++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/Sources/Sugar/Entity+Sugar.swift b/Sources/Sugar/Entity+Sugar.swift index c9d2348..d472ee3 100644 --- a/Sources/Sugar/Entity+Sugar.swift +++ b/Sources/Sugar/Entity+Sugar.swift @@ -51,3 +51,57 @@ extension Entity { try save() } } + +extension Entity where Self: SoftDeletable { + /// Saves or modifies (if already exists) a model given a value and field. + /// + /// - Parameters: + /// - value: The value to look for. + /// - field: The field to look in. + public func saveOrModify( + given value: NodeRepresentable, + for field: String, + beforeSave: ((Self, Self) -> ())? = nil, + withSoftDeleted: Bool = false, + restore: Bool = false + ) throws { + return try saveOrModify( + given: [field: value], + beforeSave: beforeSave, + withSoftDeleted: withSoftDeleted, + restore: restore + ) + } + /// Saves of modifies (if already exists) a model given multiple values and fields. + /// + /// - Parameter values: The list of values and fields to look for. + /// - Throws: On db errors. + public func saveOrModify( + given values: [String: NodeRepresentable], + beforeSave: ((Self, Self) -> ())? = nil, + withSoftDeleted: Bool = false, + restore: Bool = false + ) throws { + var query = try Self.makeQuery() + + if withSoftDeleted { + query = try query.withSoftDeleted() + } + + for (field, value) in values { + query = try query.filter(field, value) + } + if let instance = try query.first() { + id = instance.id + exists = true + if let beforeSave = beforeSave { + beforeSave(instance, self) + } + } + try save() + + if restore { + try self.restore() + } + } +}