forked from parse-community/Parse-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParseOperation.swift
480 lines (446 loc) · 18 KB
/
ParseOperation.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
//
// ParseOperation.swift
// Parse
//
// Created by Florent Vilmart on 17-07-24.
// Copyright © 2017 Parse. All rights reserved.
//
import Foundation
/**
A `ParseOperation` represents a modification to a value in a `ParseObject`.
For example, setting, deleting, or incrementing a value are all `ParseOperation`'s.
`ParseOperation` themselves can be considered to be immutable.
In most cases, you should not call this class directly as a `ParseOperation` can be
indirectly created from any `ParseObject` by using its `operation` property.
*/
public struct ParseOperation<T>: Savable where T: ParseObject {
var target: T?
var operations = [String: Encodable]()
public init(target: T) {
self.target = target
}
/**
An operation that sets a field's value if it has changed from its previous value.
- Parameters:
- key: A tuple consisting of the key and the respective KeyPath of the object.
- value: The value to set it to.
- returns: The updated operations.
*/
public func set<W>(_ key: (String, WritableKeyPath<T, W>),
value: W) throws -> Self where W: Encodable {
var mutableOperation = self
guard let target = self.target else {
throw ParseError(code: .unknownError, message: "Target shouldn't be nil")
}
if let currentValue = target[keyPath: key.1] as? NSObject,
let updatedValue = value as? NSObject {
if currentValue != updatedValue {
mutableOperation.operations[key.0] = value
mutableOperation.target?[keyPath: key.1] = value
}
} else {
mutableOperation.operations[key.0] = value
mutableOperation.target?[keyPath: key.1] = value
}
return mutableOperation
}
/**
An operation that force sets a field's value.
- Parameters:
- key: A tuple consisting of the key and the respective KeyPath of the object.
- value: The value to set it to.
- returns: The updated operations.
*/
public func forceSet<W>(_ key: (String, WritableKeyPath<T, W>),
value: W) throws -> Self where W: Encodable {
var mutableOperation = self
mutableOperation.operations[key.0] = value
mutableOperation.target?[keyPath: key.1] = value
return mutableOperation
}
/**
An operation that increases a numeric field's value by a given amount.
- Parameters:
- key: The key of the object.
- amount: How much to increment by.
- returns: The updated operations.
*/
public func increment(_ key: String, by amount: Int) -> Self {
var mutableOperation = self
mutableOperation.operations[key] = Increment(amount: amount)
return mutableOperation
}
/**
An operation that adds a new element to an array field,
only if it wasn't already present.
- Parameters:
- key: The key of the object.
- objects: The field of objects.
- returns: The updated operations.
*/
public func addUnique<W>(_ key: String, objects: [W]) -> Self where W: Encodable, W: Hashable {
var mutableOperation = self
mutableOperation.operations[key] = AddUnique(objects: objects)
return mutableOperation
}
/**
An operation that adds a new element to an array field,
only if it wasn't already present.
- Parameters:
- key: A tuple consisting of the key and the respective KeyPath of the object.
- objects: The field of objects.
- returns: The updated operations.
*/
public func addUnique<V>(_ key: (String, WritableKeyPath<T, [V]>),
objects: [V]) throws -> Self where V: Encodable, V: Hashable {
guard let target = self.target else {
throw ParseError(code: .unknownError, message: "Target shouldn't be nil")
}
var mutableOperation = self
mutableOperation.operations[key.0] = AddUnique(objects: objects)
var values = target[keyPath: key.1]
values.append(contentsOf: objects)
mutableOperation.target?[keyPath: key.1] = Array(Set<V>(values))
return mutableOperation
}
/**
An operation that adds a new element to an array field,
only if it wasn't already present.
- Parameters:
- key: A tuple consisting of the key and the respective KeyPath of the object.
- objects: The field of objects.
- returns: The updated operations.
*/
public func addUnique<V>(_ key: (String, WritableKeyPath<T, [V]?>),
objects: [V]) throws -> Self where V: Encodable, V: Hashable {
guard let target = self.target else {
throw ParseError(code: .unknownError, message: "Target shouldn't be nil")
}
var mutableOperation = self
mutableOperation.operations[key.0] = AddUnique(objects: objects)
var values = target[keyPath: key.1] ?? []
values.append(contentsOf: objects)
mutableOperation.target?[keyPath: key.1] = Array(Set<V>(values))
return mutableOperation
}
/**
An operation that adds a new element to an array field.
- Parameters:
- key: The key of the object.
- objects: The field of objects.
- returns: The updated operations.
*/
public func add<W>(_ key: String, objects: [W]) -> Self where W: Encodable {
var mutableOperation = self
mutableOperation.operations[key] = Add(objects: objects)
return mutableOperation
}
/**
An operation that adds a new element to an array field.
- Parameters:
- key: A tuple consisting of the key and the respective KeyPath of the object.
- objects: The field of objects.
- returns: The updated operations.
*/
public func add<V>(_ key: (String, WritableKeyPath<T, [V]>),
objects: [V]) throws -> Self where V: Encodable {
guard let target = self.target else {
throw ParseError(code: .unknownError, message: "Target shouldn't be nil")
}
var mutableOperation = self
mutableOperation.operations[key.0] = Add(objects: objects)
var values = target[keyPath: key.1]
values.append(contentsOf: objects)
mutableOperation.target?[keyPath: key.1] = values
return mutableOperation
}
/**
An operation that adds a new element to an array field.
- Parameters:
- key: A tuple consisting of the key and the respective KeyPath of the object.
- objects: The field of objects.
- returns: The updated operations.
*/
public func add<V>(_ key: (String, WritableKeyPath<T, [V]?>),
objects: [V]) throws -> Self where V: Encodable {
guard let target = self.target else {
throw ParseError(code: .unknownError, message: "Target shouldn't be nil")
}
var mutableOperation = self
mutableOperation.operations[key.0] = Add(objects: objects)
var values = target[keyPath: key.1] ?? []
values.append(contentsOf: objects)
mutableOperation.target?[keyPath: key.1] = values
return mutableOperation
}
/**
An operation that adds a new relation to an array field.
- Parameters:
- key: The key of the object.
- objects: The field of objects.
- returns: The updated operations.
*/
public func addRelation<W>(_ key: String, objects: [W]) throws -> Self where W: ParseObject {
var mutableOperation = self
mutableOperation.operations[key] = try AddRelation(objects: objects)
return mutableOperation
}
/**
An operation that adds a new relation to an array field.
- Parameters:
- key: A tuple consisting of the key and the respective KeyPath of the object.
- objects: The field of objects.
- returns: The updated operations.
*/
public func addRelation<V>(_ key: (String, WritableKeyPath<T, [V]>),
objects: [V]) throws -> Self where V: ParseObject {
guard let target = self.target else {
throw ParseError(code: .unknownError, message: "Target shouldn't be nil")
}
var mutableOperation = self
mutableOperation.operations[key.0] = try AddRelation(objects: objects)
var values = target[keyPath: key.1]
values.append(contentsOf: objects)
mutableOperation.target?[keyPath: key.1] = values
return mutableOperation
}
/**
An operation that adds a new relation to an array field.
- Parameters:
- key: A tuple consisting of the key and the respective KeyPath of the object.
- objects: The field of objects.
- returns: The updated operations.
*/
public func addRelation<V>(_ key: (String, WritableKeyPath<T, [V]?>),
objects: [V]) throws -> Self where V: ParseObject {
guard let target = self.target else {
throw ParseError(code: .unknownError, message: "Target shouldn't be nil")
}
var mutableOperation = self
mutableOperation.operations[key.0] = try AddRelation(objects: objects)
var values = target[keyPath: key.1] ?? []
values.append(contentsOf: objects)
mutableOperation.target?[keyPath: key.1] = values
return mutableOperation
}
/**
An operation that removes every instance of an element from
an array field.
- Parameters:
- key: The key of the object.
- objects: The field of objects.
- returns: The updated operations.
*/
public func remove<W>(_ key: String, objects: [W]) -> Self where W: Encodable {
var mutableOperation = self
mutableOperation.operations[key] = Remove(objects: objects)
return mutableOperation
}
/**
An operation that removes every instance of an element from
an array field.
- Parameters:
- key: A tuple consisting of the key and the respective KeyPath of the object.
- objects: The field of objects.
- returns: The updated operations.
*/
public func remove<V>(_ key: (String, WritableKeyPath<T, [V]>),
objects: [V]) throws -> Self where V: Encodable, V: Hashable {
guard let target = self.target else {
throw ParseError(code: .unknownError, message: "Target shouldn't be nil")
}
var mutableOperation = self
mutableOperation.operations[key.0] = Remove(objects: objects)
let values = target[keyPath: key.1]
var set = Set<V>(values)
objects.forEach {
set.remove($0)
}
mutableOperation.target?[keyPath: key.1] = Array(set)
return mutableOperation
}
/**
An operation that removes every instance of an element from
an array field.
- Parameters:
- key: A tuple consisting of the key and the respective KeyPath of the object.
- objects: The field of objects.
- returns: The updated operations.
*/
public func remove<V>(_ key: (String, WritableKeyPath<T, [V]?>),
objects: [V]) throws -> Self where V: Encodable, V: Hashable {
guard let target = self.target else {
throw ParseError(code: .unknownError, message: "Target shouldn't be nil")
}
var mutableOperation = self
mutableOperation.operations[key.0] = Remove(objects: objects)
let values = target[keyPath: key.1]
var set = Set<V>(values ?? [])
objects.forEach {
set.remove($0)
}
mutableOperation.target?[keyPath: key.1] = Array(set)
return mutableOperation
}
/**
An operation that removes every instance of a relation from
an array field.
- Parameters:
- key: The key of the object.
- objects: The field of objects.
- returns: The updated operations.
*/
public func removeRelation<W>(_ key: String, objects: [W]) throws -> Self where W: ParseObject {
var mutableOperation = self
mutableOperation.operations[key] = try RemoveRelation(objects: objects)
return mutableOperation
}
/**
An operation that removes every instance of a relation from
an array field.
- Parameters:
- key: A tuple consisting of the key and the respective KeyPath of the object.
- objects: The field of objects.
- returns: The updated operations.
*/
public func removeRelation<V>(_ key: (String, WritableKeyPath<T, [V]>),
objects: [V]) throws -> Self where V: ParseObject {
guard let target = self.target else {
throw ParseError(code: .unknownError, message: "Target shouldn't be nil")
}
var mutableOperation = self
mutableOperation.operations[key.0] = try RemoveRelation(objects: objects)
let values = target[keyPath: key.1]
var set = Set<V>(values)
objects.forEach {
set.remove($0)
}
mutableOperation.target?[keyPath: key.1] = Array(set)
return mutableOperation
}
/**
An operation that removes every instance of a relation from
an array field.
- Parameters:
- key: A tuple consisting of the key and the respective KeyPath of the object.
- objects: The field of objects.
- returns: The updated operations.
*/
public func removeRelation<V>(_ key: (String, WritableKeyPath<T, [V]?>),
objects: [V]) throws -> Self where V: ParseObject {
guard let target = self.target else {
throw ParseError(code: .unknownError, message: "Target shouldn't be nil")
}
var mutableOperation = self
mutableOperation.operations[key.0] = try RemoveRelation(objects: objects)
let values = target[keyPath: key.1]
var set = Set<V>(values ?? [])
objects.forEach {
set.remove($0)
}
mutableOperation.target?[keyPath: key.1] = Array(set)
return mutableOperation
}
/**
An operation where a field is deleted from the object.
- parameter key: The key of the object.
- returns: The updated operations.
*/
public func unset(_ key: String) -> Self {
var mutableOperation = self
mutableOperation.operations[key] = Delete()
return mutableOperation
}
/**
An operation where a field is deleted from the object.
- Parameters:
- key: A tuple consisting of the key and the respective KeyPath of the object.
- returns: The updated operations.
*/
public func unset<V>(_ key: (String, WritableKeyPath<T, V?>)) -> Self where V: Encodable {
var mutableOperation = self
mutableOperation.operations[key.0] = Delete()
mutableOperation.target?[keyPath: key.1] = nil
return mutableOperation
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: RawCodingKey.self)
try operations.forEach { pair in
let (key, value) = pair
let encoder = container.superEncoder(forKey: .key(key))
try value.encode(to: encoder)
}
}
}
extension ParseOperation {
/**
Saves the operations on 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 -> T {
guard let target = self.target else {
throw ParseError(code: .unknownError, message: "Target shouldn't be nil.")
}
if !target.isSaved {
throw ParseError(code: .missingObjectId, message: "ParseObject isn't saved.")
}
return try saveCommand()
.execute(options: options)
}
/**
Saves the operations on 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.
It should have the following argument signature: `(Result<T, ParseError>)`.
*/
public func save(
options: API.Options = [],
callbackQueue: DispatchQueue = .main,
completion: @escaping (Result<T, ParseError>) -> Void
) {
guard let target = self.target else {
callbackQueue.async {
let error = ParseError(code: .unknownError, message: "Target shouldn't be nil.")
completion(.failure(error))
}
return
}
if !target.isSaved {
callbackQueue.async {
let error = ParseError(code: .missingObjectId, message: "ParseObject isn't saved.")
completion(.failure(error))
}
return
}
do {
try self.saveCommand().executeAsync(options: options) { result in
callbackQueue.async {
completion(result)
}
}
} catch {
callbackQueue.async {
let error = ParseError(code: .missingObjectId, message: "ParseObject isn't saved.")
completion(.failure(error))
}
}
}
func saveCommand() throws -> API.NonParseBodyCommand<ParseOperation<T>, T> {
guard let target = self.target else {
throw ParseError(code: .unknownError, message: "Target shouldn't be nil")
}
return API.NonParseBodyCommand(method: .PUT, path: target.endpoint, body: self) {
try ParseCoding.jsonDecoder().decode(UpdateResponse.self, from: $0).apply(to: target)
}
}
}
// MARK: ParseOperation
public extension ParseObject {
/// Create a new operation.
var operation: ParseOperation<Self> {
return ParseOperation(target: self)
}
}