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

Commit

Permalink
Merge pull request #69 from nodes-vapor/feature/vapor-2-add-restore-f…
Browse files Browse the repository at this point in the history
…unctionality

Add support for restoring deleted entities
  • Loading branch information
steffendsommer authored Jul 16, 2018
2 parents 7f1d567 + 2087374 commit 1d48a59
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 1d48a59

Please sign in to comment.