forked from wireload/Ratatosk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWLRemoteObject.j
896 lines (756 loc) · 26.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
/*
* 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 "WLRemoteLink.j"
var WLRemoteObjectByClassByPk = {},
WLRemoteObjectDirtProof = NO;
/*!
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;
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;
}
+ (Object)_objectsByPk
{
if (WLRemoteObjectByClassByPk === nil)
WLRemoteObjectByClassByPk = {};
if (WLRemoteObjectByClassByPk[self] == undefined)
WLRemoteObjectByClassByPk[self] = {};
return WLRemoteObjectByClassByPk[self];
}
+ (id)instanceForPk:(id)pk
{
return [self instanceForPk:pk create:NO];
}
/*!
Return the object with the given PK from the register. If `create` is specified,
a new unloaded object with the given PK will be created if the PK is not yet in
the register.
If pk is nil or undefined, nil is returned.
*/
+ (id)instanceForPk:(id)pk create:(BOOL)shouldCreate
{
if (pk === nil || pk === undefined)
return nil;
var objects = [self _objectsByPk];
if (objects[pk] === undefined)
{
if (!shouldCreate)
return nil;
var object = [self new];
// Setting the pk will automatically add the object to objects[pk].
[object setPk:pk];
}
return objects[pk];
}
+ (void)setInstance:obj forPk:(id)pk
{
if (pk === nil)
return nil;
if ([obj class] !== self)
[CPException raise:CPInvalidArgumentException reason:@"" + [obj class] + " setInstance:forPk: should be used for setting " + obj + "."];
var objects = [self _objectsByPk];
objects[pk] = obj;
}
+ (CPArray)allObjects
{
r = [CPMutableArray new];
var objects = [self _objectsByPk];
for (var pk in objects)
{
if (objects.hasOwnProperty(pk))
[r addObject:objects[pk]];
}
return r;
}
+ (void)clearInstanceCache
{
WLRemoteObjectByClassByPk = {};
}
+ (void)setDirtProof:(BOOL)aFlag
{
WLRemoteObjectDirtProof = aFlag;
}
+ (BOOL)isLoadingObjects
{
// This is not the original purpose, but works out quite nicely.
return WLRemoteObjectDirtProof;
}
/*!
Specify object properties by implementing this class method on subclasses. The format is:
[
[<local property name> [, remote property name [, property transformer]]]
]
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.
*/
+ (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;
_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],
transformer = property[2];
if (!localName)
[CPException raise:CPInvalidArgumentException reason:@"Incorrect `+ (CPArray)remoteProperties` for RemoteObject classs " + [self class] + "."];
if (!remoteName)
remoteName = localName;
if (!transformer)
transformer = nil;
[remoteProperties addObject:[RemoteProperty propertyWithLocalName:localName remoteName:remoteName transformer:transformer]];
}
}
[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 _value = js[remotePkName];
if ([pkProperty valueTransformer])
_value = [[pkProperty valueTransformer] transformedValue:_value];
var existingObject = [[self class] instanceForPk:_value];
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;
}
- (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 localName]];
}
[_remoteProperties addObject:property];
[_deferredProperties addObject:property];
}
}
- (void)registerKeyForUndoManagement:(CPString)aLocalName
{
if (aLocalName == "pk")
return;
[[self undoManager] observeChangesForKeyPath:aLocalName 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 localName]];
[self addObserver:self forKeyPath:[property localName] options:nil context:property];
}
}
- (void)_autoLoad:(CPObject)anObject
{
if ([anObject respondsToSelector:@selector(ensureLoaded)])
[anObject ensureLoaded];
}
- (void)observeValueForKeyPath:(CPString)aKeyPath ofObject:(id)anObject change:(CPDictionary)change context:(id)aContext
{
var isBeforeFlag = !![change objectForKey:CPKeyValueChangeNotificationIsPriorKey];
if (isBeforeFlag)
return;
if ([change valueForKey:CPKeyValueChangeKindKey] == CPKeyValueChangeSetting && [_remoteProperties containsObject:aContext])
{
var before = [change valueForKey:CPKeyValueChangeOldKey],
after = [change valueForKey:CPKeyValueChangeNewKey],
localName = [aContext localName];
if (before !== after && ((before === nil || after === nil) || (before.isa && ![before isEqual:after])))
[self makeDirtyProperty:localName];
[_deferredProperties removeObject:aContext];
if (_shouldAutoLoad && [[self class] automaticallyLoadsRemoteObjectsForKey:localName])
{
if ([after isKindOfClass:[CPArray class]])
[after makeObjectsPerformSelector:@selector(_autoLoad:) withObject:anObject];
else
[self _autoLoad:after];
}
}
}
- (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])
{
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
{
var objectByPk = WLRemoteObjectByClassByPk[[self class]];
if (pk !== nil && objectByPk !== undefined)
delete objectByPk[pk];
pk = aPk;
[[self class] setInstance:self forPk:pk];
}
- (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 valueForKey:localName];
// Avoid calling setValue:forKey: if we just received the value we already have. This will
// happen frequently if PUT requests respond with the object representation - most fields
// will be unchanged and we don't want expensive KVO notifications to go out needlessly.
if (before !== after && ((before === nil && after !== nil) || ![before isEqual:after]))
{
// CPLog.debug("Updating property %@ from JSON (before: %@ after: %@)", localName, before, after);
[self setValue:after forKey:localName];
}
[_deferredProperties removeObject:aProperty];
}
}
- (id)asJSObjectForProperties:(CPSet)someProperties
{
var r = {};
[someProperties enumerateObjectsUsingBlock:function(aProperty)
{
var aValue = [self valueForKey:[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:[self class]])
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 the the unique path.
*/
- (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 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 || contentDownloadAction !== nil)
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
{
// 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.
if (saveAction !== nil)
{
if (![saveAction isStarted])
return;
/*
The ongoing save is saving stale information. We must ensure
another save will be scheduled after this one.
*/
_mustSaveAgain = YES;
return;
}
CPLog.info("Save " + self + " dirt: " + [[self dirtyProperties] description]);
saveAction = [WLRemoteAction schedule:WLRemoteActionPutType 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;
}
[anAction setMessage:"Saving " + [self description]];
[anAction setPayload:[self asJSObject]];
// Assume the action will succeed or retry until it does.
[self setLastSyncedAt:[CPDate date]];
_lastSyncedRevision = _revision;
[anAction setPath:[self putPath]];
}
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.
[WLRemoteObject setDirtProof:YES];
[[self undoManager] disableUndoRegistration];
[self updateFromJson:[anAction result]];
[[self undoManager] enableUndoRegistration];
[WLRemoteObject setDirtProof:NO];
contentDownloadAction = nil;
[self remoteObjectWasLoaded];
}
}
- (void)remoteObjectWasLoaded
{
if ([_delegate respondsToSelector:@selector(remoteObjectWasLoaded:)])
[_delegate remoteObjectWasLoaded:self];
}
- (void)remoteObjectWasDeleted
{
if ([_delegate respondsToSelector:@selector(remoteObjectWasDeleted:)])
[_delegate remoteObjectWasDeleted:self];
}
@end
var WLRemoteObjectClassKey = "WLRemoteObjectClassKey",
WLRemoteObjectPkKey = "WLRemoteObjectPkKey";
/*!
TODO Do something sensible here.
*/
@implementation WLRemoteObject (CPCoding)
- (id)initWithCoder:(CPCoder)aCoder
{
var clz = [aCoder decodeObjectForKey:WLRemoteObjectClassKey],
pk = [aCoder decodeObjectForKey:WLRemoteObjectPkKey];
return [WLRemoteObject instanceOf:clz withPk:pk];
}
- (void)encodeWithCoder:(CPCoder)aCoder
{
[super encodeWithCoder:aCoder];
[aCoder encodeObject:[self class] forKey:WLRemoteObjectClassKey];
[aCoder encodeObject:[self pk] forKey:WLRemoteObjectPkKey];
}
@end
@implementation RemoteProperty : CPObject
{
CPString localName @accessors;
CPString remoteName @accessors;
CPValueTransformer valueTransformer @accessors;
}
+ (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
{
var r = [RemoteProperty new];
[r setLocalName:aLocalName];
[r setRemoteName:aRemoteName];
[r setValueTransformer:aTransformer];
return r;
}
- (BOOL)isEqual:(id)anOther
{
return (anOther !== nil && anOther.isa && [anOther isKindOfClass:RemoteProperty] && anOther.localName == self.localName);
}
- (CPString)description
{
return "<RemoteProperty " + remoteName + ":" + localName + ">";
}
@end