-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathModelRepo.coffee
985 lines (792 loc) · 32.7 KB
/
ModelRepo.coffee
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
973
974
975
976
977
978
979
980
981
982
983
984
985
define [
'cord!Collection'
'cord!Model'
'cord!Module'
'cord!isBrowser'
'cord!utils/Defer'
'cord!utils/Future'
'underscore'
'monologue' + (if CORD_IS_BROWSER then '' else '.js')
], (Collection, Model, Module, isBrowser, Defer, Future, _, Monologue) ->
class ModelRepo extends Module
@include Monologue.prototype
model: Model
_collections: null
_collectedTags: null
restResource: ''
predefinedCollections: null
# @type Map[String: (Any, Any) -> Boolean]
# If it is defined for a field, the function is used as compare method for that field.
# The function must return true if values are different.
fieldCompareFunctions: null
fieldTags: null
ignoreFieldTags: false
# key-value of available additional REST-API action names to inject into model instances as methods
# key - action name
# value - HTTP-method name in lower-case (get, post, put, delete)
# @var Object[String -> String]
actions: null
@inject: ['api', 'modelProxy']
# Is this repository needs to be serialized, because it used somewhere in widgets
_used: false
constructor: (@serviceContainer) ->
throw new Error("'model' property should be set for the repository!") if not @model?
@logger = @serviceContainer.get('logger')
@_collections = {}
@_collectedTags = {}
@_initPredefinedCollections()
init: ->
_initPredefinedCollections: ->
###
Initiates hard-coded collections with their names and options based on the predefinedCollections proprerty.
###
if @predefinedCollections?
for name, options of @predefinedCollections
collection = new Collection(this, name, options)
@_registerCollection(name, collection)
createCollection: (options) ->
###
Just creates, registers and returns a new collection instance of existing collection if there is already
a registered collection with the same options.
@param Object options
@return Collection
###
if options.collectionClass
throw new Error("Extended collections should be created using ModelRepo::createExtendedCollection() method!")
name = options.collectionName or Collection.generateName(options)
if @_collections[name]? and @_collections[name].isConsistent() and not options.renew
collection = @_collections[name]
else
options = _.clone(options)
@_collections[name] = null
if _.isObject(options.rawModelsData)
options.models = []
options.models.push(@buildModel(item)) for item in options.rawModelsData
collection = new Collection(this, name, options)
@_registerCollection(name, collection)
# We need to reinject tags because some of them could be user-functions
collection.injectTags(options.tags)
collection
euthanizeCollection: (collection) ->
###
Removes collection from @_collections and clear it's cache
@return Future which resolves when cache is cleared
###
delete @_collections[collection.name]
@invalidateCollectionCache(collection.name)
createExtendedCollection: (collectionClass, options) ->
###
Creates extended collection using the given collection class. Besides just calling the class constructor
services are injected and browserInit method is called before returning the result (async).
@param Function collectionClass extended collection class constructor
@param Object options common collection options
@return Future(Collection)
###
options.collectionClass = collectionClass
name = Collection.generateName(options)
if @_collections[name]?
# We need to reinject tags because some of them could be user-functions
@_collections[name].injectTags(options.tags)
Future.resolved(@_collections[name])
else
CollectionClass = options.collectionClass ? Collection
collection = new CollectionClass(this, name, options)
@_registerCollection(name, collection)
@serviceContainer.injectServices(collection).then =>
# We need to reinject tags because some of them could be user-functions
@_collections[name].injectTags(options.tags)
collection.browserInit?() if isBrowser
collection
createSingleModel: (id, fields, extraOptions = {}) ->
###
Creates single-model collection by id and field list.
Method returns single-model collection.
@param Integer id
@param Array[String] fields list of fields names for the collection
@return Collection|null
###
# extraOptions should not override option keys defined here
options = _.extend {}, extraOptions,
id: id
fields: fields
@createCollection(options)
buildSingleModel: (id, fields, syncMode, extraOptions = {}) ->
###
Creates and syncs single-model collection by id and field list.
Method returns promise with the model instance.
:now sync mode is not available here since we need to return the resulting model.
@param {Integer} id
@param {Array<String>} fields - list of fields names for the collection
@param (optional){String} syncMode - desired sync and return mode, default to :cache
special sync mode :cache-async, tries to find model in existing collections,
if not found, calls sync in async mode to refresh model
@return {Future<Model>}
###
if syncMode == ':cache' or syncMode == ':cache-async'
model = @probeCollectionsForModel(id, fields)
if model
return Future.try =>
collection = @createCollection
renew: true # in case if we already have a model, we need to recreate the collection with the provided model
fields: fields
id: model.id
model: @buildModel(model)
collection.get(id)
syncMode = ':async' if syncMode == ':cache-async'
@createSingleModel(id, fields, extraOptions)
.sync(syncMode, 0, 0)
.then (collection) ->
collection.get(id)
probeCollectionsForModel: (id, fields) ->
###
Searches existing collections for needed model
@param Integer id - id of needed model
@param Array[String] fields list of fields names for a model
@return Object|null - model or null if not found
###
if (_.isArray fields)
matchedCollections = @scanCollections(fields)
else
matchedCollections = _.values @_collections
for collection in matchedCollections
if collection.have(id)
return collection.get(id)
null
#Get collections matching fields
scanCollections: (scannedFields) ->
_.filter @_collections, (collection, key) ->
found = 0
for field in scannedFields
if _.indexOf(collection._fields, field) > -1 || field == 'id'
found += 1
if found == scannedFields.length then true else false
sizeOfAllCollections: ->
_.reduce @_collections, (memo, value, index) ->
memo + value._models.length
, 0
scanLoadedModels: (scannedFields, searchedText, limit, requiredFields) ->
###
Scans existing collections for models, containing searchedText
@param Array[String] scannedFields - model fields to be scanned, only collections, having all the fields will be scanned
@param String searchedText
@param limit - max amout of returned models
@param Array[String] requiredFields - scan only collections with model, having all required fields
###
if !requiredFields
requiredFields = scannedFields
options=
fields: requiredFields
matchedCollections = @scanCollections(requiredFields)
result = {}
for collection in matchedCollections
foundModels = collection.scanModels scannedFields, searchedText, limit
result = _.extend result, foundModels
if limit
limit -= _.size foundModels
if limit <= 0
break
options =
fixed: true
models: result
fields: requiredFields
new Collection(this, 'fixed', options)
collectionExists: (name) ->
###
Checks if a collection with the given name is already registered in this repo
@param {String} name
@return {Boolean}
###
@_collections[name]?
getCollection: (name, returnMode, callback) ->
###
Returns registered collection by name. Returns collection immediately anyway regardless of
that given in returnMode and callback. If returnMode is given than callback is required and called
according to the returnMode value. If only callback is given, default returnMode is :now.
@param String name collection's unique (in the scope of the repository) registered name
@param (optional)String returnMode defines - when callback should be called
@param (optional)Function(Collection) callback function with the resulting collection as an argument
to be called when returnMode decides
###
if @_collections[name]?
if _.isFunction(returnMode)
callback = returnMode
returnMode = ':now'
else
returnMode or= ':now'
collection = @_collections[name]
if returnMode == ':now'
callback?(collection)
else if callback?
collection.sync(returnMode, callback)
else
throw new Error("Callback can be omitted only in case of :now return mode!")
collection
else
throw new Error("There is no registered collection with name '#{ name }'!")
_registerCollection: (name, collection) ->
###
Validates and registers the given collection
###
if @_collections[name]?
throw new Error("Collection with name '#{ name }' is already registered in #{ @constructor.__name }!")
if not (collection instanceof Collection)
throw new Error("Collection should be inherited from the base Collection class!")
@_collections[name] = collection
_fieldHasTag: (fieldName, tag) ->
@fieldTags? and @fieldTags[fieldName]? and _.isArray(@fieldTags[fieldName]) and @fieldTags[fieldName].indexOf(tag) != -1
# serialization related:
toJSON: ->
@_collections
setCollections: (collections) ->
###
Restores the repository collections from the serialized data passed from the server-side to the browser-side.
@param Object(String -> Object) collections key-value with collection name as a key and serialized collection info
as a value
@browser-only
###
@_collections = {}
promises =
for name, info of collections
do (info, name) =>
collectionClassPromise =
if info.canonicalPath?
Future.require("cord-m!#{ info.canonicalPath }")
else
Future.resolved(Collection)
collectionClassPromise.then (CollectionClass) =>
info.collectionClass = CollectionClass
collection = Collection.fromJSON(this, name, info)
#Assume that collection from backend is always fresh
collection.updateLastQueryTime()
@_registerCollection(name, collection)
@serviceContainer.injectServices(collection).then ->
collection.browserInit?()
return
Future.all(promises).then -> undefined
# REST related
query: (params, callback) ->
if @serviceContainer
apiParams = {}
url = @_buildApiRequestUrl(params)
@api.get(url, apiParams).then (response) =>
if not response._code #Bad boy! Quickfix for absence of error handling
result = []
if _.isArray(response)
result.push(@buildModel(item)) for item in response
else if response
result.push(@buildModel(response))
callback?(result)
result
else
throw new Error("#{@debug('query')}: invalid response for url '#{url}' with code #{response._code}!")
else
Future.rejected(new Error('Cleaned up'))
_buildApiRequestUrl: (params) ->
###
Build URL for api request
@param Object params paging and collection params
@return String
###
urlParams = []
urlParams.push("_sortby=#{ params.orderBy }") if params.orderBy?
if not params.id?
urlParams.push("_filter=#{ params.filterId }") if params.filterId?
urlParams.push("_filterParams=#{ params.filterParams }") if params.filterParams?
urlParams.push("_reportConfig=#{ params.reportConfig }") if params.reportConfig?
urlParams.push("_page=#{ params.page }") if params.page?
urlParams.push("_pagesize=#{ params.pageSize }") if params.pageSize?
# important! adding 1 to the params.end to compensate semantics:
# in the backend 'end' is meant as in javascript's Array.slice() - "not including"
# but in collection end is meant as the last index - "including"
urlParams.push("_slice=#{ params.start },#{ params.end + 1 }") if params.start? or params.end?
if params.filter
for filterField, filterValue of params.filter
if _.isArray filterValue
for filterValueItem in filterValue
urlParams.push("#{ filterField }[]=#{ filterValueItem }")
else
urlParams.push("#{ filterField }=#{ filterValue }")
if params.requestParams
for requestParam of params.requestParams
urlParams.push("#{ requestParam }=#{ params.requestParams[requestParam] }")
commonFields = []
calcFields = []
for field in params.fields
if @_fieldHasTag(field, ':backendCalc')
calcFields.push(field)
else
commonFields.push(field)
if commonFields.length > 0
urlParams.push("_fields=#{ commonFields.join(',') }")
else
urlParams.push("_fields=id")
urlParams.push("_calc=#{ calcFields.join(',') }") if calcFields.length > 0
@restResource + (if params.accessPoint? then ('/' + params.accessPoint) else '') + (if params.id then '/' + params.id + '/?' else '/?') + urlParams.join('&')
delete: (model) ->
###
Remove given model on the backend
@param Model model model to save
@return {Future<Object>}
###
if model.id
@api.del(@restResource + '/' + model.id).then (response) =>
@clearSingleModelCollections(model).then =>
@refreshOnlyContainingCollections(model)
response
.catch (err) =>
@emit 'error', err
throw err
else
Future.rejected(new Error("#{@debug('delete')} - model is not saved yet. Can't delete: #{model}"))
save: (model, notRefreshCollections = false) ->
###
Persists list of given models to the backend
@param model model model to save
@param notRefreshCollections - if true caller must take care of collections refreshing
@return {Future<Object>}
###
if model.id
changeInfo = model.getChangedFields()
# Don't do api request if model isn't change
if Object.keys(changeInfo).length
pureChangeInfo = _.clone(changeInfo)
changeInfo.id = model.id
changeInfo._sourceModel = model
@emit 'change', changeInfo
@api.put(@restResource + '/' + model.id, model.getChangedFields()).then (response) =>
@cacheCollection(model.collection) if model.collection?
model.resetChangedFields()
@emit 'sync', model
if not notRefreshCollections
@triggerTagsForChanges(pureChangeInfo, model)
response
.catch (err) =>
@emit 'error', err
throw err
else
Future.resolved() # todo: may be model.toJSON() would be more sufficient here?
else
@api.post(@restResource, model.getChangedFields()).then (response) =>
model.id = response.id
model.resetChangedFields()
@emit 'sync', model
@triggerTagsForNewModel(model, response) if not notRefreshCollections
@_injectActionMethods(model)
response
.catch (err) =>
@emit 'error', err
throw err
triggerTagsForNewModel: (model, response) ->
###
Merger response fields with model and trigger change.
Because backend could do anything with the fields values, like put defaults, etc
###
cloneModel = _.clone(model)
_.extend(cloneModel, response)
@triggerTagsForChanges(cloneModel, cloneModel)
triggerTagsForChanges: (changeInfo, model) ->
###
Analyse changeInfoOrModel and trigger according tags
###
model = changeInfo if changeInfo instanceof Model
@triggerTag("id.any", model)
@triggerTag("id.#{model.id}", model)
for fieldName, value of changeInfo
continue if _.isFunction(value) or not fieldName or fieldName[0] == '_' # _Ignore _any _private _parts of the object
@triggerTag("#{fieldName}.any", model)
if _.isObject(value)
if value.id
@triggerTag("#{fieldName}.#{value.id}", model)
else
@triggerTag("#{fieldName}.#{value}", model)
# Triggers tags actions on all collections
# @params tag - string
# @params mods - anythings
triggerTag: (tag, mods) ->
@_collectedTags[tag] = mods
Defer.nextTick =>
@logger.log('Emit tags:', @_collectedTags) if _.size(@_collectedTags) > 0 and global.config.debug.model
@emit('tags', @_collectedTags) if _.size(@_collectedTags) > 0
@_collectedTags = {}
paging: (params) ->
###
Requests paging information from the backend.
@param Object params paging and collection params
@return Future(Object)
total: Int (total count this collection's models)
pages: Int (total number of pages)
selected: Int (0-based index/position of the selected model)
selectedPage: Int (1-based number of the page that contains the selected model)
###
@api.get(@_buildPagingRequestUrl(params))
_buildPagingRequestUrl: (params) ->
###
Build URL for paging request
@param Object params paging and collection params
@return String
###
urlParams = []
urlParams.push("_filter=#{ params.filterId }") if params.filterId?
urlParams.push("_filterParams=#{ params.filterParams }") if params.filterParams?
urlParams.push("_reportConfig=#{ params.reportConfig }") if params.reportConfig?
urlParams.push("_pagesize=#{ params.pageSize }") if params.pageSize?
urlParams.push("_sortby=#{ params.orderBy }") if params.orderBy?
urlParams.push("_selectedId=#{ params.selectedId }") if params.selectedId
if params.filter
for filterField, filterValue of params.filter
if _.isArray filterValue
for filterValueItem in filterValue
urlParams.push("#{ filterField }[]=#{ filterValueItem }")
else
urlParams.push("#{ filterField }=#{ filterValue }")
if params.requestParams
for requestParam of params.requestParams
urlParams.push("#{ requestParam }=#{ params.requestParams[requestParam] }")
@restResource + '/paging/?' + urlParams.join('&')
###
TODO: От этого метода надо отказаться, после отказа от MixModelList
###
_buildPagingRequestParams: (params) ->
###
Build api params for paging request
@param Object params paging and collection params
@return Object
###
apiParams = {}
apiParams._pagesize = params.pageSize if params.pageSize?
apiParams._sortby = params.orderBy if params.orderBy?
apiParams._selectedId = params.selectedId if params.selectedId?
apiParams._filter = params.filterId if params.filterId?
apiParams._filterParams = params.filterParams if params.filterParams?
apiParams._reportConfig = params.reportConfig if params.reportConfig?
if params.filter
for filterField of params.filter
apiParams[filterField] = params.filter[filterField]
apiParams
emitModelChange: (model) ->
###
Call this if model's current state (not changeset) has to be propagated into all collections
@param Model - model
###
if model instanceof Model
changeInfo = model.toJSON()
changeInfo.id = model.id
else
changeInfo = model
@emit 'change', changeInfo
propagateModelChange: (model) ->
###
Model changed by set() or setAloud() method and needs to be updated in all collections
@param Model - model
###
changeInfo = model.getChangedFields()
if Object.keys changeInfo
changeInfo.id = model.id
@emit 'change', changeInfo
@suggestNewModelToCollections(model)
propagateFieldChange: (id, fieldName, newValue) ->
###
Fixes that particular field has been changed and needs to be updated in all collections
@param id Int - model id
@param fieldName String - changed field name
@param newValue mixed - new value for the object
###
#Collect field definition in all collections
fieldDefinitions = []
nameLength = fieldName.length
for key,collection of @_collections
fieldDefinitions = _.union fieldDefinitions, _.filter(collection._fields, (item) ->
item.substr(0, nameLength) == fieldName
)
if fieldDefinitions.length == 0
return
# Check if we need to make a request
needRequest = false
for fieldDefinition in fieldDefinitions
subFields = fieldDefinition.split '.'
currentValue = newValue
for i in [1..subFields.length]
if currentValue == undefined
needRequest = true
break
currentValue = currentValue[subFields[i]]
break if needRequest
#Do request, or not
Future.try =>
if needRequest
@api.get @restResource + '/' + id,
_fields: fieldDefinitions.join(',')
else
changeset = {}
changeset[fieldName] = newValue
changeset
.then (changeset) =>
#Propagate new value
changeset.id = id
for key,collection of @_collections
collection._handleModelChange changeset
return
callModelAction: (id, method, action, params) ->
###
Request REST API action method for the given model
@param Scalar id the model id
@param String action the API action name on the model
@param Object params additional key-value params for the action request (will be sent by POST)
@return Future[response]
###
@api[method]("#{ @restResource }/#{ id }/#{ action }", params)
buildModel: (attrs) ->
###
Model factory.
@param Object attrs key-value fields for the model, including the id (if exists)
@return Model
###
# Clear model and leave only fields values
if (attrs instanceof Model)
attrs = attrs.toJSON()
result = new @model(attrs)
if @modelProxy
for key, value of attrs
if Collection.isSerializedLink(value)
@modelProxy.addCollectionLink result, key
else if Model.isSerializedLink(value)
@modelProxy.addModelLink result, key
else if _.isArray(value) and Model.isSerializedLink(value[0])
@modelProxy.addArrayLink result, key
@_injectActionMethods(result) if attrs?.id
result
buildNewModel: (attrs) ->
###
Model factory.
Unlike buildModel() set input attributes in changed fields. It is important for future saving
@param Object attrs key-value fields for the model, including the id (if exists)
@return Model
###
result = new @model()
# Clear functions
safeAttrs = {}
for key, value of attrs
safeAttrs[key] = value if not _.isFunction(value)
result.set safeAttrs
@_injectActionMethods(result) if attrs?.id
result
refreshOnlyContainingCollections: (model) ->
#Make all collections, containing this model refresh
#It's cheaper than Collection::checkNewModel and ModelRepo.suggestNewModelToCollections,
#because mentioned ones make almost all collections refresh
@triggerTag('id.any', model)
@triggerTag("id.#{ model.id }", model)
refreshAll: ->
# Force refreshing all collections
# Depricated
@logger.warn('ModelRepo.refreshAll is depricated.')
Defer.nextTick =>
for name, collection of @_collections
collection.partialRefresh(1, 1, 0)
clearSingleModelCollections: (model) ->
#Clear cache and single model collections
promise = new Future('ModelRepo::clearSingleModelCollections')
for key, collection of @_collections
if parseInt(collection._id) == model.id
promise.when(collection.euthanize())
promise
invalidateAllCache: ->
###
Invalidates cache for all collections
@return {Future<undefined>}
###
for key, collection of @_collections
@_collections[key].euthanize()
if isBrowser
@serviceContainer.getService('localStorage').then (storage) =>
storage._invalidateAllCollections(@constructor.__name) #Invalidate All
else
Future.resolved()
invalidateCacheForCollectionWithField: (fieldName) ->
###
Invalidates cache for all collections with the field name
@return {Future<undefined>}
###
for key, collection of @_collections
if collection._fields.indexOf(fieldName) >= 0
@_collections[key].euthanize()
if isBrowser
@serviceContainer.getService('localStorage').then (storage) =>
storage.invalidateAllCollectionsWithField(@constructor.__name, fieldName)
else
Future.resolved()
invalidateCacheForCollectionsWithFilter: (fieldName, filterValue) ->
###
Invalidate cache for all collections where filter contains fieldName=filterVaue
###
result = new Future('ModelRepo::invalidateCacheForCollectionsWithFilter')
for key, collection of @_collections
if collection._filter[fieldName] == filterValue
if isBrowser
result.when(collection.invalidateCache())
@_collections[key].euthanize()
result
suggestNewModelToCollections: (model) ->
###
Notifies all available collections to check if they need to refresh with the new model
###
Defer.nextTick =>
for name, collection of @_collections
collection.clearLastQueryTime()
collection.checkNewModel(model, false)
_injectActionMethods: (model) ->
###
Dynamically injects syntax-sugar-methods to call REST-API actions on the model instance as method-call
with the name of the action. List of available action names must be set in the @action property of the
model repository.
@param Model model model which is injected with the methods
@return Model the incoming model with injected methods
###
if @actions?
self = this
for actionName, method of @actions
do (actionName, method) ->
model[actionName] = (params) ->
self.callModelAction(@id, method, actionName, params)
model
getTtl: ->
###
local caching related
###
600
cacheCollection: (collection) ->
###
Stores the given collection in the browser's local storage
@param {Collection} collection
@return {Future[Bool]} true if collection cached successfully, false otherwise
###
name = collection.name
if isBrowser
@serviceContainer.getService('localStorage').then (storage) =>
# prepare models for cache
collectionModels = collection.toArray()
return false if not collection.isConsistent(collectionModels)
models = []
models[i] = model.toJSON() for model, i in collectionModels
saveInfoPromise = storage.saveCollectionInfo @constructor.__name, name, collection.getTtl(),
totalCount: collection._totalCount
start: collection._loadedStart
end: collection._loadedEnd
hasLimits: collection._hasLimits
fields: collection._fields
Future.all [
saveInfoPromise
storage.saveCollection(@constructor.__name, name, models)
]
.then ->
true
.catch (err) =>
@logger.error "#{@constructor.__name}::cacheCollection() failed:", err
false
else
Future.resolved(false)
cutCachedCollection: (collection, loadedStart, loadedEnd) ->
if isBrowser
@serviceContainer.getService('localStorage').then (storage) =>
storage.saveCollectionInfo @constructor.__name, collection.name, null,
totalCount: collection._totalCount
start: loadedStart
end: loadedEnd
fields: collection._fields
else
Future.rejected(new Error('ModelRepo::cutCachedCollection is not applicable on server-side!'))
getCachedCollectionInfo: (name) ->
if isBrowser
@serviceContainer.getService('localStorage').then (storage) =>
storage.getCollectionInfo(@constructor.__name, name)
else
Future.rejected(new Error('ModelRepo::getCachedCollectionInfo is not applicable on server-side!'))
getCachedCollectionModels: (name) ->
if isBrowser
@serviceContainer.getService('localStorage').then (storage) =>
storage.getCollection(@constructor.__name, name)
.then (models) =>
result = []
for m, index in models
result[index] = @buildModel(m) if m?.id
result
else
Future.rejected(new Error('ModelRepo::getCachedCollectionModels is not applicable on server-side!'))
invalidateCollectionCache: (name) ->
if isBrowser
@serviceContainer.getService('localStorage').then (storage) =>
storage.invalidateCollection(@constructor.__name, name)
else
Future.rejected(new Error('ModelRepo::invalidateCollectionCache is not applicable on server-side!'))
_pathToObject: (pathList) ->
result = {}
for path in pathList
changePointer = result
parts = path.split('.')
lastPart = parts.pop()
# building structure based on dot-separated path
for part in parts
changePointer[part] = {}
changePointer = changePointer[part]
changePointer[lastPart] = true
result
_deepPick: (sourceObject, pattern) ->
result = {}
@_recursivePick(sourceObject, pattern, result)
_recursivePick: (src, pattern, dst) ->
for key, value of pattern
if src[key] != undefined
if value == true # leaf of this branch
dst[key] = src[key]
else if _.isObject(src[key]) # value is object, diving deeper
dst[key] = {}
if @_recursivePick(src[key], value, dst[key]) == false
return false
else
return false
else
return false
dst
_deepExtend: (args...) ->
dst = args.shift()
for src in args
@_recursiveExtend(dst, src)
dst
_recursiveExtend: (dst, src) ->
for key, value of src
if value != undefined
if dst[key] == undefined or _.isArray(value) or not _.isObject(dst[key])
dst[key] = value
else if _.isArray(value) or not _.isObject(value)
dst[key] = value
else
@_recursiveExtend(dst[key], src[key])
dst
hasFieldCompareFunction: (field) ->
###
Returns true if ModelRepo has custom compare function for the given field.
###
@fieldCompareFunctions and @fieldCompareFunctions[field]
fieldCompareFunction: (field, value1, value2) ->
###
Executes and returnes result of custom compare function for the given field and values.
###
@fieldCompareFunctions[field](value1, value2)
debug: (method) ->
###
Return identification string of the current repository for debug purposes
@param (optional) String method include optional "::method" suffix to the result
@return String
###
methodStr = if method? then "::#{ method }" else ''
"#{ @constructor.__name }#{ methodStr }"
markAsUsed: ->
###
Marks this repository as used: it should be transferred from server to browser in this case
###
@_used = true
isUsed: ->
###
Is this repository used in anywhere. If yes, it should be transferred from server to browser
###
@_used