Skip to content
This repository has been archived by the owner on Apr 20, 2024. It is now read-only.

Commit

Permalink
Add support for restoring deleted entities
Browse files Browse the repository at this point in the history
  • Loading branch information
steffendsommer committed Jul 16, 2018
1 parent 7f1d567 commit 2087374
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions Sources/Sugar/Entity+Sugar.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
}
}

0 comments on commit 2087374

Please sign in to comment.