Skip to content

Commit 6753bd4

Browse files
authored
Merge pull request #148 from raulriera/callbacks-fix
Callbacks fix to prevent data loss
2 parents 270ea92 + 9e48d22 commit 6753bd4

File tree

2 files changed

+72
-4
lines changed

2 files changed

+72
-4
lines changed

Sources/Fluent/Query/Query.swift

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -197,15 +197,14 @@ extension QueryRepresentable {
197197
*/
198198
public func save(_ model: inout T) throws {
199199
let query = try makeQuery()
200-
let data = try model.makeNode()
201-
200+
202201
if let _ = model.id, model.exists {
203202
model.willUpdate()
204-
try modify(data)
203+
try modify(model.makeNode())
205204
model.didUpdate()
206205
} else {
207206
model.willCreate()
208-
model.id = try query.create(data)
207+
model.id = try query.create(model.makeNode())
209208
model.didCreate()
210209
}
211210
model.exists = true
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import XCTest
2+
@testable import Fluent
3+
4+
class CallbacksTests: XCTestCase {
5+
6+
/// Dummy Model implementation for testing.
7+
final class DummyModel: Entity {
8+
var exists: Bool = false
9+
var wasModifiedOnCreate: Bool = false
10+
var wasModifiedOnUpdate: Bool = false
11+
12+
static func prepare(_ database: Database) throws {}
13+
static func revert(_ database: Database) throws {}
14+
15+
var id: Node?
16+
17+
init() {
18+
19+
}
20+
21+
init(node: Node, in context: Context) throws {
22+
23+
}
24+
25+
func makeNode(context: Context = EmptyNode) -> Node {
26+
return .null
27+
}
28+
29+
func willCreate() {
30+
wasModifiedOnCreate = true
31+
}
32+
33+
func willUpdate() {
34+
wasModifiedOnUpdate = true
35+
}
36+
}
37+
38+
static let allTests = [
39+
("testCreateCallbacksCanMutateProperties", testCreateCallbacksCanMutateProperties),
40+
("testUpdateCallbacksCanMutateProperties", testUpdateCallbacksCanMutateProperties)
41+
]
42+
43+
override func setUp() {
44+
database = Database(DummyDriver())
45+
Database.default = database
46+
}
47+
48+
var database: Database!
49+
50+
func testCreateCallbacksCanMutateProperties() {
51+
var result = DummyModel()
52+
XCTAssertFalse(result.wasModifiedOnCreate, "Result should not have been modified yet")
53+
54+
try? result.save()
55+
XCTAssertTrue(result.wasModifiedOnCreate, "Result should have been modified by now")
56+
}
57+
58+
func testUpdateCallbacksCanMutateProperties() {
59+
var result = DummyModel()
60+
XCTAssertFalse(result.wasModifiedOnUpdate, "Result should not have been modified yet")
61+
62+
try? result.save()
63+
XCTAssertFalse(result.wasModifiedOnUpdate, "Result should not have been modified yet")
64+
65+
// Save the object once more to trigger the update callback
66+
try? result.save()
67+
XCTAssertTrue(result.wasModifiedOnUpdate, "Result should have been modified by now")
68+
}
69+
}

0 commit comments

Comments
 (0)