forked from wireload/Ratatosk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WLRemoteObject.j
972 lines (813 loc) · 30.8 KB
/
WLRemoteObject.j
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
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
/*
* WLRemoteObject.j
* Ratatosk
*
* Created by Alexander Ljungberg on November 16, 2009.
* Copyright 2009-11, WireLoad Inc. All rights reserved.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided
* with the distribution. Neither the name of WireLoad Inc. nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
@import "WLRemoteContext.j"
@import "WLRemoteLink.j"
var WLRemoteObjectDirtProof = NO,
CamelCaseToHyphenPrefixStripper = new RegExp('^[_A-Z]+([A-Z])'),
CamelCaseToHyphenator = new RegExp("([a-z])([A-Z])");
/*!
Compare a and b whether a is CPObject or JS primitive.
*/
var isEqual = function(a, b) {
if (a == nil || b == nil || !a.isa)
return a === b;
return [a isEqual:b];
}
function CamelCaseToHyphenated(camelCase)
{
return camelCase.replace(CamelCaseToHyphenPrefixStripper, '$1').replace(CamelCaseToHyphenator, '$1-$2').toLowerCase();
};
/*!
A WLRemoteObject is a proxy object meant to be synced with a remote object
through an API and a WLRemoteLink. Every WLRemoteObject must have a
unique primary key which can be the REST URI of the object (as a
CPString) or a database numeric id. The exception is for new objects
have nil as their PK.
A WLRemoteObject is equal to another WLRemoteObject with the same class
and key. The object supports loading and saving from and to JSON and
keeps automatic track of which properties are dirty and need to be saved.
By default, objects autosave when simple properties are changed.
Subclasses must implement:
+ (CPArray)remoteProperties
Subclasses might want to implement:
- (void)remotePath
*/
@implementation WLRemoteObject : CPObject
{
id pk @accessors;
CPString _remoteName @accessors(readonly, property=remoteName);
CPSet _remoteProperties @accessors(readonly, property=remoteProperties);
Object _propertyLastRevision;
CPSet _deferredProperties;
int _revision;
int _lastSyncedRevision;
CPDate lastSyncedAt @accessors;
WLRemoteAction createAction;
WLRemoteAction saveAction;
WLRemoteAction deleteAction;
WLRemoteAction contentDownloadAction;
BOOL _shouldAutoSave @accessors(property=shouldAutoSave);
BOOL _shouldAutoLoad @accessors(property=shouldAutoLoad);
BOOL _suppressAutoSave;
BOOL _suppressRemotePropertiesObservation;
BOOL _mustSaveAgain;
id _delegate @accessors(property=delegate);
CPUndoManager undoManager @accessors;
}
/*!
Deprectated. Use `[[WLRemoteContext sharedRemoteContext] registeredObjectForRemoteName:[self remoteName] withPk:pk]`.
*/
+ (id)instanceForPk:(id)pk
{
if (pk === nil || pk === undefined)
return nil;
return [[WLRemoteContext sharedRemoteContext] registeredObjectForRemoteName:[self remoteName] withPk:pk];
}
/*!
Deprectated. Use `[[WLRemoteContext sharedRemoteContext] registeredObjectForRemoteName:[self remoteName] withPk:pk]`.
*/
+ (id)instanceForPk:(id)pk create:(BOOL)shouldCreate
{
if (pk === nil || pk === undefined)
return nil;
var r = [self instanceForPk:pk];
if (r === nil && shouldCreate)
{
r = [self new];
// Setting the pk will automatically register it.
[r setPk:pk];
}
return r;
}
/*!
Deprecated. Use `[[WLRemoteContext sharedRemoteContext] registeredObjectsForRemoteName:[self remoteName]]`.
*/
+ (CPArray)allObjects
{
return [[WLRemoteContext sharedRemoteContext] registeredObjectsForRemoteName:[self remoteName]];
}
+ (void)clearInstanceCache
{
[CPException raise:CPInvalidArgumentException reason:@"Use [WLRemoteContext reset] instead."];
}
+ (void)setDirtProof:(BOOL)aFlag
{
WLRemoteObjectDirtProof = aFlag;
}
+ (BOOL)isLoadingObjects
{
// This is not the original purpose, but works out quite nicely.
return WLRemoteObjectDirtProof;
}
/*!
The name of the remote resource. The name of the resource combined with the PK of an instance is what uniquely identifies a specific resource. (For many APIs the PK is the resource URI and alone uniquely identifies the resource, but for APIs where the PK is something like an ID number the name is critical so that e.g. User 101 is not considered the same remote object as BlogPost 101.)
If two classes are alternative implementations for the same remote resource, they should have the same remote name. E.g. if there is a remote resource called a "Shape" and two classes "Circle" and "Rectangle" implement two types of "Shape", their remoteName should be "shape" so that Ratatosk can recognise that both circles and rectangles should go in the same "bucket" of objects.
By default the remoteName is the class name minus any leading prefix and converted from camelcase to lowercase with dashes. E.g. a remote object class like WLBlogPost would by default have a remoteName of 'blog-post'.
*/
+ (CPString)remoteName
{
var className = CPStringFromClass([self class]);
return CamelCaseToHyphenated(className);
}
/*!
Specify object properties by implementing this class method on subclasses. The format is:
[
[<local property name> [, remote property name [, property transformer[, load only?]]]]
]
If no remote property name is specified, the local property name is used as the remote property
name.
At a minimum the PK property has to be defined.
Load only properties are read from the server but never written back, even if the property
is changed locally. For instance, you might have a value which the server derives from other
values, so it's effectively read-only server side. But you know how to derive this value too,
so when you make local changes you want to immediately update your local value, thereby
changing it in the client. But you can't write that back to the server. Load-only will ensure
the property is READ from the server but never WRITTEN. Load-only properties do not affect
the object isDirty status and do not participate in automatic undo management.
The 'pk' property is automatically considered load only.
*/
+ (CPArray)remoteProperties
{
return [
['pk', 'id']
];
}
+ (CPArray)objectsFromJson:jsonArray
{
var r = [CPArray array];
for (var i = 0; i < jsonArray.length; i++)
{
[r addObject:[[self alloc] initWithJson:jsonArray[i]]];
}
return r;
}
/*!
When shouldAutoLoad is YES and this method returns YES for a property, any remote
object set to that property will have `ensureLoaded` automatically called.
*/
+ (BOOL)automaticallyLoadsRemoteObjectsForKey:(CPString)aLocalName
{
var capitalizedName = aLocalName.charAt(0).toUpperCase() + aLocalName.substring(1),
selector = "automaticallyLoadsRemoteObjectsFor" + capitalizedName;
if ([[self class] respondsToSelector:selector])
return objj_msgSend([self class], selector);
return NO;
}
- (id)init
{
if (self = [super init])
{
_revision = 0;
_lastSyncedRevision = -1;
_shouldAutoSave = YES;
_shouldAutoLoad = YES;
_remoteName = [[self class] remoteName];
_remoteProperties = [CPSet set];
_propertyLastRevision = {};
_deferredProperties = [CPSet set];
lastSyncedAt = [CPDate distantPast];
var remoteProperties = [],
otherProperties = [[self class] remoteProperties];
if (otherProperties)
{
for (var i = 0, count = [otherProperties count]; i < count; i++)
{
var property = otherProperties[i],
localName = property[0],
remoteName = property[1] || localName,
transformer = property[2] || nil,
loadOnly = (typeof property[3] !== "undefined") ? property[3] : localName == "pk" || NO;
if (!localName)
[CPException raise:CPInvalidArgumentException reason:@"Incorrect `+ (CPArray)remoteProperties` for RemoteObject class " + [self class] + "."];
[remoteProperties addObject:[RemoteProperty propertyWithLocalName:localName remoteName:remoteName transformer:transformer loadOnly:loadOnly]];
}
}
[self registerRemoteProperties:remoteProperties];
}
return self;
}
- (id)initWithJson:(id)js
{
_suppressRemotePropertiesObservation = YES;
if (self = [self init])
{
// (This should always be true)
if (pk === nil || pk === undefined)
{
// Check if the JSON is for an instance we are already tracking.
var pkProperty = [self pkProperty],
remotePkName = [pkProperty remoteName];
if (js[remotePkName] !== undefined)
{
var pkValue = js[remotePkName];
if ([pkProperty valueTransformer])
pkValue = [[pkProperty valueTransformer] transformedValue:pkValue];
var existingObject = [[self context] registeredObjectForRemoteName:[self remoteName] withPk:pkValue];
if (existingObject)
{
// Yes we are tracking an existing object. Update that object instead and return it.
self = existingObject;
[existingObject updateFromJson:js];
return self;
}
}
}
[self updateFromJson:js];
_suppressRemotePropertiesObservation = NO;
[self activateRemotePropertiesObservation];
}
return self;
}
- (WLRemoteContext)context
{
// For future compatibility when there can be multiple contexts.
return [WLRemoteContext sharedRemoteContext];
}
- (void)registerRemoteProperties:(CPArray)someProperties
{
for (var i = 0, count = [someProperties count]; i < count; i++)
{
var property = someProperties[i];
if ([_remoteProperties containsObject:property])
continue;
if (!_suppressRemotePropertiesObservation)
{
[self addObserver:self forKeyPath:[property localName] options:nil context:property];
// FIXME Since the undo manager is no longer read from a central place, this will do nothing.
// This action needs to be taken when setUndoManager: is received instead.
[self registerKeyForUndoManagement:property];
}
[_remoteProperties addObject:property];
[_deferredProperties addObject:property];
}
}
- (void)registerKeyForUndoManagement:(RemoteProperty)aProperty
{
if ([aProperty isLoadOnly])
return;
[[self undoManager] observeChangesForKeyPath:[aProperty localName] ofObject:self];
}
- (void)pkProperty
{
return [self remotePropertyForKey:"pk"];
}
- (RemoteProperty)remotePropertyForKey:(CPString)aLocalName
{
var remotePropertiesEnumerator = [_remoteProperties objectEnumerator],
property;
while (property = [remotePropertiesEnumerator nextObject])
if ([property localName] == aLocalName)
return property;
return nil;
}
- (void)activateRemotePropertiesObservation
{
var remotePropertiesEnumerator = [_remoteProperties objectEnumerator],
property;
while (property = [remotePropertiesEnumerator nextObject])
{
[self registerKeyForUndoManagement:property];
[self addObserver:self forKeyPath:[property localName] options:nil context:property];
if (_shouldAutoLoad && [[self class] automaticallyLoadsRemoteObjectsForKey:[property localName]])
{
if ([[self valueForKeyPath:[property localName]] isKindOfClass:[CPArray class]])
[[self valueForKeyPath:[property localName]] makeObjectsPerformSelector:@selector(ensureLoaded)];
else
[[self valueForKeyPath:[property localName]] ensureLoaded];
}
}
}
- (void)observeValueForKeyPath:(CPString)aKeyPath ofObject:(id)anObject change:(CPDictionary)change context:(id)aContext
{
var isBeforeFlag = !![change objectForKey:CPKeyValueChangeNotificationIsPriorKey];
if (isBeforeFlag)
return;
if ([_remoteProperties containsObject:aContext])
{
var localName = [aContext localName],
kind = [change objectForKey:CPKeyValueChangeKindKey],
after = [change objectForKey:CPKeyValueChangeNewKey];
if (kind === CPKeyValueChangeSetting)
{
var before = [change objectForKey:CPKeyValueChangeOldKey];
if (!isEqual(before, after))
[self makeDirtyProperty:localName];
[_deferredProperties removeObject:aContext];
if (_shouldAutoLoad && [[self class] automaticallyLoadsRemoteObjectsForKey:localName])
{
if ([after isKindOfClass:[CPArray class]])
[after makeObjectsPerformSelector:@selector(ensureLoaded)];
else
[after ensureLoaded];
}
}
else if (kind === CPKeyValueChangeInsertion || kind === CPKeyValueChangeReplacement)
{
[self makeDirtyProperty:localName];
if (_shouldAutoLoad && [[self class] automaticallyLoadsRemoteObjectsForKey:localName])
[after makeObjectsPerformSelector:@selector(ensureLoaded)];
}
}
}
- (void)cleanAll
{
_propertyLastRevision = {};
}
- (void)cleanProperty:(CPString)localName
{
delete _propertyLastRevision[localName];
}
- (void)makeAllDirty
{
var remotePropertiesEnumerator = [_remoteProperties objectEnumerator],
property;
while (property = [remotePropertiesEnumerator nextObject])
{
[self makeDirtyProperty:[property localName]]
}
}
- (void)makeDirtyProperty:(CPString)localName
{
if (WLRemoteObjectDirtProof)
return;
_propertyLastRevision[localName] = ++_revision;
if (!_suppressAutoSave && ![self isNew] && _shouldAutoSave)
{
// Run the check for whether we should autosave at the end of the
// run loop so that batch changes can collate. This also enables
// the [object setProperty:X];[object cleanAll]; without having to
// suppress auto saves.
[[CPRunLoop currentRunLoop] performSelector:"ensureSaved" target:self argument:nil order:0 modes:[CPDefaultRunLoopMode]];
}
}
/*!
Mark the named property as not yet having been downloaded so that [instance ensureLoaded] will cause it to be redownloaded.
You might do this if you know a property has updated server side and needs to be reread.
*/
- (void)invalidateProperty:(CPString)localName
{
var property = [self remotePropertyForKey:localName];
if (property == nil)
[CPException raise:CPInvalidArgumentException reason:@"Unknown property " + localName + "."];
delete _propertyLastRevision[localName];
[_deferredProperties addObject:property];
}
- (BOOL)isDirty
{
return [[self dirtyProperties] count] > 0;
}
- (CPSet)dirtyProperties
{
var r = [CPSet set],
property = nil,
objectEnumerator = [_remoteProperties objectEnumerator];
while (property = [objectEnumerator nextObject])
{
if ([property isLoadOnly])
continue;
var localName = [property localName];
if (_propertyLastRevision[localName] && _propertyLastRevision[localName] > _lastSyncedRevision)
[r addObject:property];
}
return r;
}
/*!
Every property begins 'deferred', meaning unloaded. When a property is set
through initWithJson, updateFromJson, or a mutator, it is no longer considered
deferred.
*/
- (BOOL)isPropertyDeferred:(CPString)localName
{
var property = [self remotePropertyForKey:localName];
if (!property)
[CPException raise:CPInvalidArgumentException reason:@"Unknown property " + localName + "."];
return [_deferredProperties containsObject:property];
}
- (BOOL)isPropertyDirty:(CPString)localName
{
return _propertyLastRevision[localName] && _propertyLastRevision[localName] > _lastSyncedRevision;
}
- (void)setPk:(id)aPk
{
if (pk === aPk)
return;
var context = [self context];
[context unregisterObject:self];
pk = aPk;
if (pk)
[context registerObject:self];
}
- (void)updateFromJson:js
{
var property = nil,
objectEnumerator = [_remoteProperties objectEnumerator];
while (property = [objectEnumerator nextObject])
[self updateFromJson:js remoteProperty:property];
}
- (void)updateFromJson:js preservingDirtyProperties:(BOOL)shouldPreserveDirty
{
var property = nil,
objectEnumerator = [_remoteProperties objectEnumerator];
while (property = [objectEnumerator nextObject])
{
// If the local version is changed, don't overwrite it with the remote.
if (shouldPreserveDirty && [[self dirtyProperties] containsObject:property])
continue;
[self updateFromJson:js remoteProperty:property];
}
}
- (void)updateFromJson:js remoteProperty:(RemoteProperty)aProperty
{
var remoteName = [aProperty remoteName];
if (js[remoteName] !== undefined)
{
var after = js[remoteName],
localName = [aProperty localName];
if ([aProperty valueTransformer])
after = [[aProperty valueTransformer] transformedValue:after];
var before = [self valueForKeyPath:localName];
// Avoid calling setValue:forKey: if we just received the value we already have. This will
// happen frequently if `PUT` / `PATCH` requests respond with the object representation - most fields
// will be unchanged and we don't want expensive KVO notifications to go out needlessly.
if (!isEqual(before, after))
{
// CPLog.debug("Updating property %@ from JSON (before: %@ after: %@)", localName, before, after);
[self setValue:after forKeyPath:localName];
}
[_deferredProperties removeObject:aProperty];
}
}
- (id)asJSObjectForProperties:(CPSet)someProperties
{
var r = {};
[someProperties enumerateObjectsUsingBlock:function(aProperty)
{
var aValue = [self valueForKeyPath:[aProperty localName]],
aValueTransformer = [aProperty valueTransformer];
if (aValueTransformer && [[aValueTransformer class] allowsReverseTransformation])
aValue = [aValueTransformer reverseTransformedValue:aValue];
r[[aProperty remoteName]] = aValue;
}
];
return r;
}
- (id)asPatchJSObject
{
return [self asJSObjectForProperties:[self dirtyProperties]];
}
- (id)asJSObject
{
return [self asJSObjectForProperties:[self remoteProperties]];
}
- (BOOL)isEqual:(id)anObject
{
if (self === anObject)
return YES;
if (![anObject isKindOfClass:WLRemoteObject])
return NO;
if (![[anObject remoteName] isEqual:[self remoteName]])
return NO;
// Entries with no primary key can only be equal if they
// are identical.
if ([self pk] === nil)
return NO;
return [self pk] == [anObject pk];
}
/*!
The path of this resource within the API. The path should not include the path to the API root (see WLRemoteLink).
By default, the PK is assumed to be the canonical resource URI.
*/
- (CPString)remotePath
{
return [self pk];
}
/*!
The path to use when GETing (downloading) this resource. By default this is [self remotePath].
*/
- (CPString)getPath
{
return [self remotePath];
}
/*!
The path to use when POSTing (creating) a new resource. By default this is [self remotePath].
*/
- (CPString)postPath
{
return [self remotePath];
}
/*!
The path to use when PUTting (updating) this resource. By default this is [self remotePath].
*/
- (CPString)putPath
{
return [self remotePath];
}
/*!
The path to use when PATCHing (updating) this resource. By default this is [self remotePath].
*/
- (CPString)patchPath
{
return [self remotePath];
}
/*!
The path to use when DELETEing this resource. By default this is [self remotePath].
*/
- (CPString)deletePath
{
return [self remotePath];
}
- (BOOL)isNew
{
return pk === nil || pk === undefined;
}
/*!
Create or recreate this object remotely.
*/
- (void)create
{
[[self undoManager] registerUndoWithTarget:self
selector:@selector(delete)
object:nil];
[self ensureCreated];
}
/*!
Delete this object remotely.
*/
- (void)delete
{
[[self undoManager] registerUndoWithTarget:self
selector:@selector(create)
object:nil];
[self ensureDeleted];
}
- (void)ensureCreated
{
if (![self isNew] || createAction !== nil)
return;
// FIXME Should this be here or in init somewhere? In init we don't yet know if
// this object will be loaded from remote or if it's being created.
// Since we're creating the object, there are no deferred fields. Without clearing
// these, ensureLoaded would lead to a pointless GET.
_deferredProperties = [CPSet set];
// Also consider all fields dirty so that any initial values get POSTed. E.g. if a new
// RemoteObject has a title attribute like 'unnamed' by default, that should be transmitted
// to the server.
[self makeAllDirty];
createAction = [WLRemoteAction schedule:WLRemoteActionPostType path:[self postPath] delegate:self message:"Create " + [self description]];
}
- (void)ensureDeleted
{
if ([self isNew] || deleteAction !== nil)
return;
// Path might not be known yet. A delete can be scheduled before the object has been created. The path will be
// set in remoteActionWillBegin when the path must be known.
deleteAction = [WLRemoteAction schedule:WLRemoteActionDeleteType path:nil delegate:self message:"Delete " + [self description]];
}
- (void)ensureLoaded
{
if ([self isNew] || [_deferredProperties count] == 0)
return;
[self reload];
}
/*!
Reload the properties of this resource from the server. Also see `ensureLoaded` which only causes the resource to
be retrieved if it hasn't already been fully downloaded.
*/
- (void)reload
{
// We're only interested in most recent GET actions.
if (contentDownloadAction && ![contentDownloadAction isStarted])
[contentDownloadAction cancel];
// Path might not be known yet. A load can be scheduled before the object has been created. The path will be
// set in remoteActionWillBegin when the path must be known.
contentDownloadAction = [WLRemoteAction schedule:WLRemoteActionGetType path:nil delegate:self message:"Loading " + [self description]];
}
- (void)ensureSaved
{
if (![self isDirty])
return;
// If a save action is already in the pipe, relax. Same if the object is about to be created - we'll transfer up to date
// information once the creation action fires.
if (createAction !== nil || saveAction !== nil)
{
if (![createAction isStarted] && ![saveAction isStarted])
return;
/*
The ongoing save is saving stale information. We must ensure
another save will be scheduled after this one.
*/
_mustSaveAgain = YES;
return;
}
var dirtDescription = [[[[self dirtyProperties] valueForKeyPath:@"localName"] allObjects] componentsJoinedByString:@", "];
CPLog.info("Save " + [self description] + " dirt: " + dirtDescription);
saveAction = [WLRemoteAction schedule:[[[self context] remoteLink] saveActionType] path:nil delegate:self message:"Save " + [self description]];
}
- (void)remoteActionWillBegin:(WLRemoteAction)anAction
{
if (anAction === createAction)
{
if (pk)
{
CPLog.error("Attempt to create an existing object");
return;
}
[anAction setPayload:[self asJSObject]];
// Assume the action will succeed or retry until it does.
[self setLastSyncedAt:[CPDate date]];
_lastSyncedRevision = _revision;
}
else if (anAction === deleteAction)
{
if (pk === nil)
{
CPLog.error("Attempt to delete a non existant object");
return;
}
[anAction setPayload:nil];
// Assume the action will succeed or retry until it does.
[self setLastSyncedAt:[CPDate date]];
_lastSyncedRevision = _revision;
[anAction setPath:[self deletePath]];
}
else if (anAction === saveAction)
{
if (!pk)
{
CPLog.error("Attempt to save non created object " + [self description]);
return;
}
var patchAction = [anAction type] === WLRemoteActionPatchType;
[anAction setMessage:"Saving " + [self description]];
[anAction setPayload:patchAction ? [self asPatchJSObject] : [self asJSObject]];
[anAction setPath:patchAction ? [self patchPath] : [self putPath]];
// Assume the action will succeed or retry until it does.
[self setLastSyncedAt:[CPDate date]];
_lastSyncedRevision = _revision;
}
else if (anAction === contentDownloadAction)
{
[anAction setPath:[self getPath]];
}
}
- (void)remoteActionDidReceiveResourceRepresentation:(Object)aResult
{
[WLRemoteObject setDirtProof:YES];
[[self undoManager] disableUndoRegistration];
// Take any data received from the POST/PUT/PATCH and update the object correspondingly -
// in particular we might need any primary key that was generated. We could also get new
// data for updated_at style fields.
// At the same time we don't want to overwrite any changes the user made while the request
// was processing, so we preserve dirty properties here.
[self updateFromJson:aResult preservingDirtyProperties:YES];
[[self undoManager] enableUndoRegistration];
[WLRemoteObject setDirtProof:NO];
}
- (void)remoteActionDidFinish:(WLRemoteAction)anAction
{
if (anAction === createAction)
{
[self remoteActionDidReceiveResourceRepresentation:[anAction result]];
createAction = nil;
if ([_delegate respondsToSelector:@selector(remoteObjectWasCreated:)])
[_delegate remoteObjectWasCreated:self];
}
else if (anAction === deleteAction)
{
// The previous PK is now gone.
[self setPk:nil];
// There is nothing to save anymore.
[saveAction cancel];
saveAction = nil;
// After the object has been deleted, the next call to 'ensureCreated' will
// create a new object. When that creation happens all the data should be
// considered dirty to ensure it gets sent with the creation.
[self makeAllDirty];
deleteAction = nil;
[self remoteObjectWasDeleted];
}
else if (anAction === saveAction)
{
if ([anAction result])
[self remoteActionDidReceiveResourceRepresentation:[anAction result]];
saveAction = nil;
if (_mustSaveAgain)
{
_mustSaveAgain = NO;
[self ensureSaved];
}
}
else if (anAction === contentDownloadAction)
{
// Assume whatever was downloaded is the most current info, so nothing gets dirty.
[self remoteActionDidReceiveResourceRepresentation:[anAction result]];
contentDownloadAction = nil;
[self remoteObjectWasLoaded];
}
}
- (void)remoteObjectWasLoaded
{
if ([_delegate respondsToSelector:@selector(remoteObjectWasLoaded:)])
[_delegate remoteObjectWasLoaded:self];
}
- (void)remoteObjectWasDeleted
{
if ([_delegate respondsToSelector:@selector(remoteObjectWasDeleted:)])
[_delegate remoteObjectWasDeleted:self];
}
#pragma mark CPObject
- (CPString)description
{
return "<" + [self class] + " " + [self UID] + (pk ? " " + pk : "") + ">";
}
@end
@implementation WLRemoteObject (CPCoding)
- (id)initWithCoder:(CPCoder)aCoder
{
if (self = [self init])
{
pk = [aCoder decodeObjectForKey:@"$pk"];
if (pk)
{
var existingObject = [[self class] instanceForPk:pk];
if (existingObject)
return existingObject;
}
[_remoteProperties enumerateObjectsUsingBlock:function(aProperty, idx)
{
[self setValue:[aCoder decodeObjectForKey:"$" + [aProperty localName]] forKeyPath:[aProperty localName]];
}];
}
return self;
}
- (void)encodeWithCoder:(CPCoder)aCoder
{
[_remoteProperties enumerateObjectsUsingBlock:function(aProperty, idx)
{
[aCoder encodeObject:[self valueForKeyPath:[aProperty localName]] forKey:"$" + [aProperty localName]];
}];
}
@end
@implementation RemoteProperty : CPObject
{
CPString localName @accessors;
CPString remoteName @accessors;
CPValueTransformer valueTransformer @accessors;
BOOL loadOnly @accessors(getter=isLoadOnly);
}
+ (id)propertyWithName:(CPString)aName
{
return [self propertyWithLocalName:aName remoteName:aName transformer:nil];
}
+ (id)propertyWithLocalName:(CPString)aLocalName remoteName:(CPString)aRemoteName
{
return [self propertyWithLocalName:aLocalName remoteName:aRemoteName transformer:nil];
}
+ (id)propertyWithLocalName:(CPString)aLocalName remoteName:(CPString)aRemoteName transformer:(CPValueTransformer)aTransformer loadOnly:(boolean)shouldBeLoadOnly
{
var r = [RemoteProperty new];
[r setLocalName:aLocalName];
[r setRemoteName:aRemoteName];
[r setValueTransformer:aTransformer];
[r setLoadOnly:shouldBeLoadOnly];
return r;
}
- (BOOL)isEqual:(id)anOther
{
return (anOther !== nil && anOther.isa && [anOther isKindOfClass:RemoteProperty] && anOther.localName == self.localName);
}
- (CPString)description
{
return "<RemoteProperty " + remoteName + ":" + localName + (loadOnly ? " (load-only)" : "") + ">";
}
@end