-
-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathParseObject.swift
872 lines (810 loc) · 41 KB
/
ParseObject.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
//
// ParseObject.swift
// ParseSwift
//
// Created by Florent Vilmart on 17-07-24.
// Copyright © 2020 Parse. All rights reserved.
//
import Foundation
/**
Objects that conform to the `ParseObject` protocol have a local representation of data persisted to the Parse cloud.
This is the main protocol that is used to interact with objects in your app.
If you plan to use custom encoding/decoding, be sure to add `objectId`, `createdAt`, `updatedAt`, and
`ACL` to your `ParseObject` `CodingKeys`.
- note: It is recommended to make your`ParseObject`s "value types" (structs).
If you are using value types there isn't much else you need to do but to conform to ParseObject. If you are thinking of
using reference types, see the warning.
- warning: If you plan to use "reference types" (classes), you are using at your risk as this SDK is not designed
for reference types and may have unexpected behavior when it comes to threading. You will also need to implement
your own `==` method to conform to `Equatable` along with with the `hash` method to conform to `Hashable`.
It is important to note that for unsaved `ParseObject`'s, you won't be able to rely on `objectId` for
`Equatable` and `Hashable` as your unsaved objects won't have this value yet and is nil. A possible way to
address this is by creating a `UUID` for your objects locally and relying on that for `Equatable` and `Hashable`,
otherwise it's possible you will get "circular dependency errors" depending on your implementation.
*/
public protocol ParseObject: Objectable,
Fetchable,
Savable,
Deletable,
Hashable,
CustomDebugStringConvertible,
CustomStringConvertible {
}
// MARK: Default Implementations
public extension ParseObject {
/**
Determines if two objects have the same objectId.
- parameter as: Object to compare.
- returns: Returns a `true` if the other object has the same `objectId` or `false` if unsuccessful.
*/
func hasSameObjectId<T: ParseObject>(as other: T) -> Bool {
return other.className == className && other.objectId == objectId && objectId != nil
}
/**
Gets a Pointer referencing this object.
- returns: Pointer<Self>
*/
func toPointer() throws -> Pointer<Self> {
return try Pointer(self)
}
}
// MARK: Batch Support
public extension Sequence where Element: ParseObject {
/**
Saves a collection of objects *synchronously* all at once and throws an error if necessary.
- parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched.
is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`.
Defaults to 50.
- parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that
prevents the transaction from completing, then none of the objects are committed to the Parse Server database.
- parameter isIgnoreCustomObjectIdConfig: Ignore checking for `objectId`
when `ParseConfiguration.allowCustomObjectId = true` to allow for mixed
`objectId` environments. Defaults to false.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- returns: Returns a Result enum with the object if a save was successful or a `ParseError` if it failed.
- throws: `ParseError`
- warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the
objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else
the transactions can fail.
- warning: If you are using `ParseConfiguration.allowCustomObjectId = true`
and plan to generate all of your `objectId`'s on the client-side then you should leave
`isIgnoreCustomObjectIdConfig = false`. Setting
`ParseConfiguration.allowCustomObjectId = true` and
`isIgnoreCustomObjectIdConfig = true` means the client will generate `objectId`'s
and the server will generate an `objectId` only when the client does not provide one. This can
increase the probability of colliiding `objectId`'s as the client and server `objectId`'s may be generated using
different algorithms. This can also lead to overwriting of `ParseObject`'s by accident as the
client-side checks are disabled. Developers are responsible for handling such cases.
*/
func saveAll(batchLimit limit: Int? = nil, // swiftlint:disable:this function_body_length
transaction: Bool = false,
isIgnoreCustomObjectIdConfig: Bool = false,
options: API.Options = []) throws -> [(Result<Self.Element, ParseError>)] {
var options = options
options.insert(.cachePolicy(.reloadIgnoringLocalCacheData))
var childObjects = [String: PointerType]()
var childFiles = [UUID: ParseFile]()
var error: ParseError?
let objects = map { $0 }
for object in objects {
let group = DispatchGroup()
group.enter()
object.ensureDeepSave(options: options) { (savedChildObjects, savedChildFiles, parseError) -> Void in
//If an error occurs, everything should be skipped
if parseError != nil {
error = parseError
}
savedChildObjects.forEach {(key, value) in
if error != nil {
return
}
if childObjects[key] == nil {
childObjects[key] = value
} else {
error = ParseError(code: .unknownError, message: "circular dependency")
return
}
}
savedChildFiles.forEach {(key, value) in
if error != nil {
return
}
if childFiles[key] == nil {
childFiles[key] = value
} else {
error = ParseError(code: .unknownError, message: "circular dependency")
return
}
}
group.leave()
}
group.wait()
if let error = error {
throw error
}
}
var returnBatch = [(Result<Self.Element, ParseError>)]()
let commands = try map { try $0.saveCommand(isIgnoreCustomObjectIdConfig: isIgnoreCustomObjectIdConfig) }
let batchLimit: Int!
if transaction {
batchLimit = commands.count
} else {
batchLimit = limit ?? ParseConstants.batchLimit
}
let batches = BatchUtils.splitArray(commands, valuesPerSegment: batchLimit)
try batches.forEach {
let currentBatch = try API.Command<Self.Element, Self.Element>
.batch(commands: $0, transaction: transaction)
.execute(options: options,
callbackQueue: .main,
childObjects: childObjects,
childFiles: childFiles)
returnBatch.append(contentsOf: currentBatch)
}
return returnBatch
}
/**
Saves a collection of objects all at once *asynchronously* and executes the completion block when done.
- parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched.
is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`.
Defaults to 50.
- parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that
prevents the transaction from completing, then none of the objects are committed to the Parse Server database.
- parameter isIgnoreCustomObjectIdConfig: Ignore checking for `objectId`
when `ParseConfiguration.allowCustomObjectId = true` to allow for mixed
`objectId` environments. Defaults to false.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- parameter callbackQueue: The queue to return to after completion. Default value of .main.
- parameter completion: The block to execute.
It should have the following argument signature: `(Result<[(Result<Element, ParseError>)], ParseError>)`.
- warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the
objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else
the transactions can fail.
- warning: If you are using `ParseConfiguration.allowCustomObjectId = true`
and plan to generate all of your `objectId`'s on the client-side then you should leave
`isIgnoreCustomObjectIdConfig = false`. Setting
`ParseConfiguration.allowCustomObjectId = true` and
`isIgnoreCustomObjectIdConfig = true` means the client will generate `objectId`'s
and the server will generate an `objectId` only when the client does not provide one. This can
increase the probability of colliiding `objectId`'s as the client and server `objectId`'s may be generated using
different algorithms. This can also lead to overwriting of `ParseObject`'s by accident as the
client-side checks are disabled. Developers are responsible for handling such cases.
*/
func saveAll( // swiftlint:disable:this function_body_length cyclomatic_complexity
batchLimit limit: Int? = nil,
transaction: Bool = false,
isIgnoreCustomObjectIdConfig: Bool = false,
options: API.Options = [],
callbackQueue: DispatchQueue = .main,
completion: @escaping (Result<[(Result<Element, ParseError>)], ParseError>) -> Void
) {
var options = options
options.insert(.cachePolicy(.reloadIgnoringLocalCacheData))
let uuid = UUID()
let queue = DispatchQueue(label: "com.parse.saveAll.\(uuid)",
qos: .default,
attributes: .concurrent,
autoreleaseFrequency: .inherit,
target: nil)
queue.sync {
var childObjects = [String: PointerType]()
var childFiles = [UUID: ParseFile]()
var error: ParseError?
let objects = map { $0 }
for object in objects {
let group = DispatchGroup()
group.enter()
object.ensureDeepSave(options: options) { (savedChildObjects, savedChildFiles, parseError) -> Void in
//If an error occurs, everything should be skipped
if parseError != nil {
error = parseError
}
savedChildObjects.forEach {(key, value) in
if error != nil {
return
}
if childObjects[key] == nil {
childObjects[key] = value
} else {
error = ParseError(code: .unknownError, message: "circular dependency")
return
}
}
savedChildFiles.forEach {(key, value) in
if error != nil {
return
}
if childFiles[key] == nil {
childFiles[key] = value
} else {
error = ParseError(code: .unknownError, message: "circular dependency")
return
}
}
group.leave()
}
group.wait()
if let error = error {
callbackQueue.async {
completion(.failure(error))
}
return
}
}
do {
var returnBatch = [(Result<Self.Element, ParseError>)]()
let commands = try map {
try $0.saveCommand(isIgnoreCustomObjectIdConfig: isIgnoreCustomObjectIdConfig)
}
let batchLimit: Int!
if transaction {
batchLimit = commands.count
} else {
batchLimit = limit ?? ParseConstants.batchLimit
}
let batches = BatchUtils.splitArray(commands, valuesPerSegment: batchLimit)
var completed = 0
for batch in batches {
API.Command<Self.Element, Self.Element>
.batch(commands: batch, transaction: transaction)
.executeAsync(options: options,
callbackQueue: callbackQueue,
childObjects: childObjects,
childFiles: childFiles) { results in
switch results {
case .success(let saved):
returnBatch.append(contentsOf: saved)
if completed == (batches.count - 1) {
callbackQueue.async {
completion(.success(returnBatch))
}
}
completed += 1
case .failure(let error):
callbackQueue.async {
completion(.failure(error))
}
return
}
}
}
} catch {
callbackQueue.async {
if let parseError = error as? ParseError {
completion(.failure(parseError))
} else {
completion(.failure(.init(code: .unknownError, message: error.localizedDescription)))
}
}
}
}
}
/**
Fetches a collection of objects *synchronously* all at once and throws an error if necessary.
- parameter includeKeys: The name(s) of the key(s) to include that are
`ParseObject`s. Use `["*"]` to include all keys. This is similar to `include` and
`includeAll` for `Query`.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- returns: Returns a Result enum with the object if a fetch was successful or a `ParseError` if it failed.
- throws: `ParseError`
- warning: The order in which objects are returned are not guarenteed. You shouldn't expect results in
any particular order.
*/
func fetchAll(includeKeys: [String]? = nil,
options: API.Options = []) throws -> [(Result<Self.Element, ParseError>)] {
if (allSatisfy { $0.className == Self.Element.className}) {
let uniqueObjectIds = Set(compactMap { $0.objectId })
var query = Self.Element.query(containedIn(key: "objectId", array: [uniqueObjectIds]))
.limit(uniqueObjectIds.count)
if let include = includeKeys {
query = query.include(include)
}
let fetchedObjects = try query.find(options: options)
var fetchedObjectsToReturn = [(Result<Self.Element, ParseError>)]()
uniqueObjectIds.forEach {
let uniqueObjectId = $0
if let fetchedObject = fetchedObjects.first(where: {$0.objectId == uniqueObjectId}) {
fetchedObjectsToReturn.append(.success(fetchedObject))
} else {
fetchedObjectsToReturn.append(.failure(ParseError(code: .objectNotFound,
// swiftlint:disable:next line_length
message: "objectId \"\(uniqueObjectId)\" was not found in className \"\(Self.Element.className)\"")))
}
}
return fetchedObjectsToReturn
} else {
throw ParseError(code: .unknownError, message: "all items to fetch must be of the same class")
}
}
/**
Fetches a collection of objects all at once *asynchronously* and executes the completion block when done.
- parameter includeKeys: The name(s) of the key(s) to include that are
`ParseObject`s. Use `["*"]` to include all keys. This is similar to `include` and
`includeAll` for `Query`.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- parameter callbackQueue: The queue to return to after completion. Default value of .main.
- parameter completion: The block to execute.
It should have the following argument signature: `(Result<[(Result<Element, ParseError>)], ParseError>)`.
- warning: The order in which objects are returned are not guarenteed. You shouldn't expect results in
any particular order.
*/
func fetchAll(
includeKeys: [String]? = nil,
options: API.Options = [],
callbackQueue: DispatchQueue = .main,
completion: @escaping (Result<[(Result<Element, ParseError>)], ParseError>) -> Void
) {
if (allSatisfy { $0.className == Self.Element.className}) {
let uniqueObjectIds = Set(compactMap { $0.objectId })
var query = Self.Element.query(containedIn(key: "objectId", array: [uniqueObjectIds]))
if let include = includeKeys {
query = query.include(include)
}
query.find(options: options, callbackQueue: callbackQueue) { result in
switch result {
case .success(let fetchedObjects):
var fetchedObjectsToReturn = [(Result<Self.Element, ParseError>)]()
uniqueObjectIds.forEach {
let uniqueObjectId = $0
if let fetchedObject = fetchedObjects.first(where: {$0.objectId == uniqueObjectId}) {
fetchedObjectsToReturn.append(.success(fetchedObject))
} else {
fetchedObjectsToReturn.append(.failure(ParseError(code: .objectNotFound,
// swiftlint:disable:next line_length
message: "objectId \"\(uniqueObjectId)\" was not found in className \"\(Self.Element.className)\"")))
}
}
callbackQueue.async {
completion(.success(fetchedObjectsToReturn))
}
case .failure(let error):
callbackQueue.async {
completion(.failure(error))
}
}
}
} else {
callbackQueue.async {
completion(.failure(ParseError(code: .unknownError,
message: "all items to fetch must be of the same class")))
}
}
}
/**
Deletes a collection of objects *synchronously* all at once and throws an error if necessary.
- parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched.
is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`.
Defaults to 50.
- parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that
prevents the transaction from completing, then none of the objects are committed to the Parse Server database.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- returns: Returns `nil` if the delete successful or a `ParseError` if it failed.
1. A `ParseError.Code.aggregateError`. This object's "errors" property is an
array of other Parse.Error objects. Each error object in this array
has an "object" property that references the object that could not be
deleted (for instance, because that object could not be found).
2. A non-aggregate Parse.Error. This indicates a serious error that
caused the delete operation to be aborted partway through (for
instance, a connection failure in the middle of the delete).
- throws: `ParseError`
- warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the
objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else
the transactions can fail.
*/
func deleteAll(batchLimit limit: Int? = nil,
transaction: Bool = false,
options: API.Options = []) throws -> [(Result<Void, ParseError>)] {
var options = options
options.insert(.cachePolicy(.reloadIgnoringLocalCacheData))
var returnBatch = [(Result<Void, ParseError>)]()
let commands = try map { try $0.deleteCommand() }
let batchLimit: Int!
if transaction {
batchLimit = commands.count
} else {
batchLimit = limit ?? ParseConstants.batchLimit
}
let batches = BatchUtils.splitArray(commands, valuesPerSegment: batchLimit)
try batches.forEach {
let currentBatch = try API.Command<Self.Element, (Result<Void, ParseError>)>
.batch(commands: $0, transaction: transaction)
.execute(options: options)
returnBatch.append(contentsOf: currentBatch)
}
return returnBatch
}
/**
Deletes a collection of objects all at once *asynchronously* and executes the completion block when done.
- parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched.
is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`.
Defaults to 50.
- parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that
prevents the transaction from completing, then none of the objects are committed to the Parse Server database.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- parameter callbackQueue: The queue to return to after completion. Default value of .main.
- parameter completion: The block to execute.
It should have the following argument signature: `(Result<[ParseError?], ParseError>)`.
Each element in the array is `nil` if the delete successful or a `ParseError` if it failed.
1. A `ParseError.Code.aggregateError`. This object's "errors" property is an
array of other Parse.Error objects. Each error object in this array
has an "object" property that references the object that could not be
deleted (for instance, because that object could not be found).
2. A non-aggregate Parse.Error. This indicates a serious error that
caused the delete operation to be aborted partway through (for
instance, a connection failure in the middle of the delete).
- warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the
objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else
the transactions can fail.
*/
func deleteAll(
batchLimit limit: Int? = nil,
transaction: Bool = false,
options: API.Options = [],
callbackQueue: DispatchQueue = .main,
completion: @escaping (Result<[(Result<Void, ParseError>)], ParseError>) -> Void
) {
do {
var options = options
options.insert(.cachePolicy(.reloadIgnoringLocalCacheData))
var returnBatch = [(Result<Void, ParseError>)]()
let commands = try map({ try $0.deleteCommand() })
let batchLimit: Int!
if transaction {
batchLimit = commands.count
} else {
batchLimit = limit ?? ParseConstants.batchLimit
}
let batches = BatchUtils.splitArray(commands, valuesPerSegment: batchLimit)
var completed = 0
for batch in batches {
API.Command<Self.Element, ParseError?>
.batch(commands: batch, transaction: transaction)
.executeAsync(options: options) { results in
switch results {
case .success(let saved):
returnBatch.append(contentsOf: saved)
if completed == (batches.count - 1) {
callbackQueue.async {
completion(.success(returnBatch))
}
}
completed += 1
case .failure(let error):
callbackQueue.async {
completion(.failure(error))
}
return
}
}
}
} catch {
callbackQueue.async {
guard let parseError = error as? ParseError else {
completion(.failure(ParseError(code: .unknownError,
message: error.localizedDescription)))
return
}
completion(.failure(parseError))
}
}
}
}
// MARK: CustomDebugStringConvertible
extension ParseObject {
public var debugDescription: String {
guard let descriptionData = try? ParseCoding.jsonEncoder().encode(self),
let descriptionString = String(data: descriptionData, encoding: .utf8) else {
return "\(className) ()"
}
return "\(className) (\(descriptionString))"
}
}
// MARK: CustomStringConvertible
extension ParseObject {
public var description: String {
debugDescription
}
}
// MARK: Fetchable
extension ParseObject {
/**
Fetches the `ParseObject` *synchronously* with the current data from the server and sets an error if one occurs.
- parameter includeKeys: The name(s) of the key(s) to include that are
`ParseObject`s. Use `["*"]` to include all keys. This is similar to `include` and
`includeAll` for `Query`.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- throws: An error of `ParseError` type.
*/
public func fetch(includeKeys: [String]? = nil,
options: API.Options = []) throws -> Self {
try fetchCommand(include: includeKeys).execute(options: options,
callbackQueue: .main)
}
/**
Fetches the `ParseObject` *asynchronously* and executes the given callback block.
- parameter includeKeys: The name(s) of the key(s) to include. Use `["*"]` to include
all keys.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- parameter callbackQueue: The queue to return to after completion. Default
value of .main.
- parameter completion: The block to execute when completed.
It should have the following argument signature: `(Result<Self, ParseError>)`.
*/
public func fetch(
includeKeys: [String]? = nil,
options: API.Options = [],
callbackQueue: DispatchQueue = .main,
completion: @escaping (Result<Self, ParseError>) -> Void
) {
do {
try fetchCommand(include: includeKeys)
.executeAsync(options: options,
callbackQueue: callbackQueue) { result in
callbackQueue.async {
completion(result)
}
}
} catch {
callbackQueue.async {
if let error = error as? ParseError {
completion(.failure(error))
} else {
completion(.failure(ParseError(code: .unknownError,
message: error.localizedDescription)))
}
}
}
}
internal func fetchCommand(include: [String]?) throws -> API.Command<Self, Self> {
try API.Command<Self, Self>.fetch(self, include: include)
}
}
// MARK: Savable
extension ParseObject {
/**
Saves the `ParseObject` *synchronously* and throws an error if there's an issue.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- throws: An error of type `ParseError`.
- returns: Returns saved `ParseObject`.
*/
public func save(options: API.Options = []) throws -> Self {
try save(isIgnoreCustomObjectIdConfig: false, options: options)
}
/**
Saves the `ParseObject` *synchronously* and throws an error if there's an issue.
- parameter isIgnoreCustomObjectIdConfig: Ignore checking for `objectId`
when `ParseConfiguration.allowCustomObjectId = true` to allow for mixed
`objectId` environments. Defaults to false.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- throws: An error of type `ParseError`.
- returns: Returns saved `ParseObject`.
- warning: If you are using `ParseConfiguration.allowCustomObjectId = true`
and plan to generate all of your `objectId`'s on the client-side then you should leave
`isIgnoreCustomObjectIdConfig = false`. Setting
`ParseConfiguration.allowCustomObjectId = true` and
`isIgnoreCustomObjectIdConfig = true` means the client will generate `objectId`'s
and the server will generate an `objectId` only when the client does not provide one. This can
increase the probability of colliiding `objectId`'s as the client and server `objectId`'s may be generated using
different algorithms. This can also lead to overwriting of `ParseObject`'s by accident as the
client-side checks are disabled. Developers are responsible for handling such cases.
*/
public func save(isIgnoreCustomObjectIdConfig: Bool = false,
options: API.Options = []) throws -> Self {
var childObjects: [String: PointerType]?
var childFiles: [UUID: ParseFile]?
var error: ParseError?
var options = options
options.insert(.cachePolicy(.reloadIgnoringLocalCacheData))
let group = DispatchGroup()
group.enter()
self.ensureDeepSave(options: options) { (savedChildObjects, savedChildFiles, parseError) in
childObjects = savedChildObjects
childFiles = savedChildFiles
error = parseError
group.leave()
}
group.wait()
if let error = error {
throw error
}
return try saveCommand(isIgnoreCustomObjectIdConfig: isIgnoreCustomObjectIdConfig)
.execute(options: options,
callbackQueue: .main,
childObjects: childObjects,
childFiles: childFiles)
}
/**
Saves the `ParseObject` *asynchronously* and executes the given callback block.
- parameter isIgnoreCustomObjectIdConfig: Ignore checking for `objectId`
when `ParseConfiguration.allowCustomObjectId = true` to allow for mixed
`objectId` environments. Defaults to false.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- parameter callbackQueue: The queue to return to after completion. Default value of .main.
- parameter completion: The block to execute.
It should have the following argument signature: `(Result<Self, ParseError>)`.
- warning: If you are using `ParseConfiguration.allowCustomObjectId = true`
and plan to generate all of your `objectId`'s on the client-side then you should leave
`isIgnoreCustomObjectIdConfig = false`. Setting
`ParseConfiguration.allowCustomObjectId = true` and
`isIgnoreCustomObjectIdConfig = true` means the client will generate `objectId`'s
and the server will generate an `objectId` only when the client does not provide one. This can
increase the probability of colliiding `objectId`'s as the client and server `objectId`'s may be generated using
different algorithms. This can also lead to overwriting of `ParseObject`'s by accident as the
client-side checks are disabled. Developers are responsible for handling such cases.
*/
public func save(
isIgnoreCustomObjectIdConfig: Bool = false,
options: API.Options = [],
callbackQueue: DispatchQueue = .main,
completion: @escaping (Result<Self, ParseError>) -> Void
) {
self.ensureDeepSave(options: options) { (savedChildObjects, savedChildFiles, error) in
guard let parseError = error else {
do {
try self.saveCommand(isIgnoreCustomObjectIdConfig: isIgnoreCustomObjectIdConfig)
.executeAsync(options: options,
callbackQueue: callbackQueue,
childObjects: savedChildObjects,
childFiles: savedChildFiles) { result in
callbackQueue.async {
completion(result)
}
}
} catch {
callbackQueue.async {
if let parseError = error as? ParseError {
completion(.failure(parseError))
} else {
completion(.failure(.init(code: .unknownError, message: error.localizedDescription)))
}
}
}
return
}
callbackQueue.async {
completion(.failure(parseError))
}
}
}
internal func saveCommand(isIgnoreCustomObjectIdConfig: Bool = false) throws -> API.Command<Self, Self> {
try API.Command<Self, Self>.save(self, isIgnoreCustomObjectIdConfig: isIgnoreCustomObjectIdConfig)
}
// swiftlint:disable:next function_body_length
internal func ensureDeepSave(options: API.Options = [],
completion: @escaping ([String: PointerType],
[UUID: ParseFile], ParseError?) -> Void) {
let uuid = UUID()
let queue = DispatchQueue(label: "com.parse.deepSave.\(uuid)",
qos: .default,
attributes: .concurrent,
autoreleaseFrequency: .inherit,
target: nil)
var options = options
options.insert(.cachePolicy(.reloadIgnoringLocalCacheData))
queue.sync {
var objectsFinishedSaving = [String: PointerType]()
var filesFinishedSaving = [UUID: ParseFile]()
do {
let object = try ParseCoding.parseEncoder()
.encode(self,
objectsSavedBeforeThisOne: nil,
filesSavedBeforeThisOne: nil)
var waitingToBeSaved = object.unsavedChildren
while waitingToBeSaved.count > 0 {
var savableObjects = [ParseType]()
var savableFiles = [ParseFile]()
var nextBatch = [ParseType]()
try waitingToBeSaved.forEach { parseType in
if let parseFile = parseType as? ParseFile {
//ParseFiles can be saved now
savableFiles.append(parseFile)
} else if let parseObject = parseType as? Objectable {
//This is a ParseObject
let waitingObjectInfo = try ParseCoding
.parseEncoder()
.encode(parseObject,
collectChildren: true,
objectsSavedBeforeThisOne: objectsFinishedSaving,
filesSavedBeforeThisOne: filesFinishedSaving)
if waitingObjectInfo.unsavedChildren.count == 0 {
//If this ParseObject has no additional children, it can be saved now
savableObjects.append(parseObject)
} else {
//Else this ParseObject needs to wait until it's children are saved
nextBatch.append(parseObject)
}
}
}
waitingToBeSaved = nextBatch
if waitingToBeSaved.count > 0 && savableObjects.count == 0 && savableFiles.count == 0 {
completion(objectsFinishedSaving,
filesFinishedSaving,
ParseError(code: .unknownError,
message: "Found a circular dependency in ParseObject."))
return
}
if savableObjects.count > 0 {
let savedChildObjects = try self.saveAll(objects: savableObjects,
options: options)
let savedChildPointers = try savedChildObjects.compactMap { try $0.get() }
for (index, object) in savableObjects.enumerated() {
let hash = try BaseObjectable.createHash(object)
objectsFinishedSaving[hash] = savedChildPointers[index]
}
}
try savableFiles.forEach {
filesFinishedSaving[$0.localId] = try $0.save(options: options, callbackQueue: queue)
}
}
completion(objectsFinishedSaving, filesFinishedSaving, nil)
} catch {
guard let parseError = error as? ParseError else {
completion(objectsFinishedSaving, filesFinishedSaving,
ParseError(code: .unknownError,
message: error.localizedDescription))
return
}
completion(objectsFinishedSaving, filesFinishedSaving, parseError)
}
}
}
}
// MARK: Savable Encodable Version
internal extension ParseType {
func saveAll(objects: [ParseType],
transaction: Bool = ParseSwift.configuration.useTransactionsInternally,
options: API.Options = []) throws -> [(Result<PointerType, ParseError>)] {
try API.NonParseBodyCommand<AnyCodable, PointerType>
.batch(objects: objects,
transaction: transaction)
.execute(options: options)
}
}
// MARK: Deletable
extension ParseObject {
/**
Deletes the `ParseObject` *synchronously* with the current data from the server and sets an error if one occurs.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- throws: An error of `ParseError` type.
*/
public func delete(options: API.Options = []) throws {
_ = try deleteCommand().execute(options: options)
}
/**
Deletes the `ParseObject` *asynchronously* and executes the given callback block.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- parameter callbackQueue: The queue to return to after completion. Default
value of .main.
- parameter completion: The block to execute when completed.
It should have the following argument signature: `(Result<Void, ParseError>)`.
*/
public func delete(
options: API.Options = [],
callbackQueue: DispatchQueue = .main,
completion: @escaping (Result<Void, ParseError>) -> Void
) {
do {
try deleteCommand().executeAsync(options: options) { result in
callbackQueue.async {
switch result {
case .success:
completion(.success(()))
case .failure(let error):
completion(.failure(error))
}
}
}
} catch let error as ParseError {
callbackQueue.async {
completion(.failure(error))
}
} catch {
callbackQueue.async {
completion(.failure(ParseError(code: .unknownError, message: error.localizedDescription)))
}
}
}
internal func deleteCommand() throws -> API.NonParseBodyCommand<NoBody, NoBody> {
try API.NonParseBodyCommand<NoBody, NoBody>.delete(self)
}
} // swiftlint:disable:this file_length