This repository was archived by the owner on Aug 15, 2022. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathindex.coffee
More file actions
executable file
·916 lines (888 loc) · 30 KB
/
Copy pathindex.coffee
File metadata and controls
executable file
·916 lines (888 loc) · 30 KB
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
###
Bongo.js
Unfancy models for MongoDB
(c) 2011 Koding, Inc.
@class: Model
@description: A class for modeling, validating,
transforming, saving, finding and sharing data.
The model klass of the library.
@author: Christopher Thorn <chris@koding.com>
###
Base = require '../base'
module.exports = class Model extends Base
###
@dependencies.
###
# core
{inspect} = require 'util'
# contrib
mongo = require 'mongoskin'
Traverse = require 'traverse'
{extend, clone} = require 'underscore'
MongoOp = require 'mongoop'
{sequence} = require 'sinkrow'
Inflector = require 'inflector'
# lib
JsPath = require '../jspath'
ObjectId = require '../objectid'
Subcollection = require '../subcollection'
Validator = require '../validator'
# err
{SchemaError, IndexError} = require '../errortypes'
###
@vars.
###
# defineProperty
{defineProperty} = Object
# native JS casts
primitives = [
String
Number
Boolean
]
# native JS constructors
natives = [
Object
RegExp
Date
]
###
@method: property of the constructor
@signature: Model.setDontAutoCastId(true|false)
@description: By default, bongo will automatically cast strings
that it finds inside a field called "_id" as BSON ObjectIds.
This works great for most cases, and adds a layer of convenience
(you don't need to import ObjectId and manually cast the value),
but could potentially be problematic if you want to store another
type of value in the "_id" field, which MongoDB doesn't prohibit
you from doing. In that case, set this flag to true (directly,
or by invoking this method with the parameter "true").
###
@setDontAutoCastId =(@dontAutoCastId=false)->
###
@method: property of the constructor
@signature: setValidators(validators)
@todo: implement
###
@setValidators =(validators)->
###
@method: property of the constructor
@signature: setBricks(validators)
@todo: implement
###
@setBricks =(bricks)->
###
@method: property of the constructor
@signature: Model.setClient(*overload)
@overload:
@signature: Model.setClient(client)
@param: client - an instance of the Db constructor from mongodb native.
@overload:
@signature: Model.setClient(url)
@param: url - of the mongodb.
@overload:
@signature: Model.setClient(options)
@param: options - initializer for the connetion.
@options:
- server
- username
- password
- database
- port
@return: the constuctor
@description: basically, it registers a connection with the Model
class for the purpose of saving and finding data.
@todo: do we want an instance method that will allow certain instances
to have their own separate connection? It is convenient to have this
registered at the class-level, for obvious reasons. It is maybe too
abstract, tho.
###
@setClient =(overload, shouldConnect=yes)->
constructor = @
{SkinDb} = mongo
if overload instanceof SkinDb
client = overload
else
unless 'string' is typeof overload
{server, username, password, database, port} = overload
auth = if username and password then "#{username}:#{password}@" else ''
# TODO: this is obviously botched ^.
overload = "#{auth}#{server}:#{port}/#{database}"
client = mongo.db overload, safe: no
unless constructor.client_?
defineProperty constructor, 'client_',
value: client
writable: yes
else
constructor.client_ = client
unless Model.client_?
Model.setClient client
#constructor.onReady null, client
@getClient =-> @client_ or Model.client_
@setCollectionName =(@collection_)->
@getCollectionName =->
@collection_ or= Inflector.decapitalize Inflector.pluralize @name
@getCollection =->
client = @getClient()
unless client
throw new Error \
"""
You must set the client for this constructor, or failing that, you must set a generic client for Model.
"""
client.collection @getCollectionName()
@setTeaserFields =(fieldList)->
@teaserFields = {}
for field in fieldList
@teaserFields[field] = yes
###
@method: property of the constructor.
@signature: Model.setIndexes([indexes][, callback])
@return: the constructor.
###
@setIndexes = do ->
###
@vars.
@description: index orientation fudge tests
###
ascending_ = /^(asc|ascending|1)$/i
descending_ = /^(desc|descending|-1)$/i
construeOrientation =(attr)->
attr = String(attr).toLowerCase()
if ascending_.test attr then 1
else if descending_.test attr then -1
else 0
(indexes, callback)->
if 'function' is typeof indexes
[callback, indexes] = [indexes, callback]
constructor = @
if indexes
defineProperty constructor, 'indexes', value: indexes
else
{indexes} = constructor
unless indexes
throw new Error \
"""
No indexes were provided. (At least one is required.)
"""
figureIndex = sequence (collection, key, attrs, next)->
field = {}
def = {}
field[key] = null
if 'string' is typeof attrs
attrs = [attrs]
for attr in attrs
if orientation = construeOrientation attr
field[key] = orientation
else
def[attr] = yes
field[key] or= 1
# ensure the index
collection.ensureIndex field, def, (err)->
next? err
return
return
, callback
process.nextTick ->
collection = constructor.getCollection()
for own key, attrs of indexes
figureIndex collection, key, attrs
return
constructor
@reIndex =(callback)->
constructor = @
process.nextTick ->
constructor.getCollection().dropIndexes (err)->
if err
callback? err
else
constructor.setIndexes callback
return
return
return
###
@method: property of the constructor.
@signature: Model.setSchema(schema)
###
@describeSchema =->
{keys} = Object
{types, subcollections} = this
(keys types ? {})
.map (slot)->
type = types[slot].name
slot = slot.replace /\.0$/, -> type = [type]; ''
[slot, type]
.reduce (acc, [slot, type])->
JsPath.setAt acc, slot, type
acc
, {}
###
@method: property of the constructor.
@signature: Model.setSchema(schema)
@param: schema - ^3
@return: the constructor.
@description: sets a constructor property "schema"^3. sets constructor
properties for each memo to help quicken traversal of important paths
(without walking the entire schema).
###
@setSchema = (schema)->
if @ is Model
throw new SchemaError "Don't define a schema for Model, which is abstract."
# track a reference to the constructor so we can look it up by name.
constructor = @
defineProperty constructor, 'validators_',
value: clone Validator.inbuilts
# store a reference to the human-readable schema
defineProperty constructor, 'schema',
value: schema
# memoize the important bits for easy lookup
for own memoName, memo of constructor.getMemosOf schema
defineProperty constructor, memoName,
enumerable: yes
value: memo
@
###
@method: property of the constructor.
@signature: Model.getMemosOf(schema)
@param: schema - ^3
@return: the map of memos by path.
@description: walk over the schema, interpreting it along the way
and finding the notable items and annotations, and mapping memos
of them by their paths; then return the maps of all the memos by
by path by memo name.
@todo: this implementation is really long.
###
accessorNames = ['get','set']
@getMemosOf = (schema)->
constructor = @
memos =
paths : {}
filters : {}
# broadcastChanges : {} # TODO: implement leaf-level broadcastChanges
types : {}
subcollections : {}
subcollectionEmbeds : {}
validators : {}
annotations : {}
primitives : {}
natives : {}
embeds : {}
oids : {}
defaults : {}
setters : {}
getters : {}
accessorParents : {}
rootProperties : []
new Traverse(schema)
.forEach ->
{node, path} = @
pathName = path.join '.'
memos.paths[pathName] = yes # this path exists in the schema
if path.length is 1
if path[0] is 'globalFlags' then #console.log node
memos.rootProperties.push pathName
if 'function' isnt typeof node
if Array.isArray node
unless node.length is 1 and 'function' is typeof node[0]
throw new SchemaError \
"""
Can't interpret #{constructor.name}.schema.#{pathName}.
"""
else
memos.subcollections[pathName] = node[0]
else if 'function' is typeof node.type #^5
# type is a described by the "type" property
# this opens the doorway for some more complex (than type-only) annotations
@update node, yes # we don't want to traverse any deeper into this thing.
type = node.type
if node.default?
memos.defaults[pathName] = node.default
if node.filter?
memos.filters[pathName] = node.filter
# TODO: implement leaf-level broadcastChanges
# memos.broadcastChanges[pathName] =
# if node.broadcastChanges?
# node.broadcastChanges
# else yes
# memoize any validators
leafValidators = []
for own validatorName, validator of constructor.validators_
options = node[validatorName]
if options?
leafValidators.push new Validator validator, options
# memoize validators:
if leafValidators.length
memos.validators[pathName] = leafValidators
# memoize any accessors:
for accessor in accessorNames
if node[accessor]
unless 'function' is typeof node[accessor]
throw new SchemaError \
"""
"#{accessor}" is not a function
"""
memos["#{accessor}ters"][path] = node[accessor]
accessorParentPath = ['_data'].concat path.slice 0, -1
parent = memos.accessorParents[accessorParentPath.join '.'] or= []
parent.push path unless path in parent
else if node.name #^4
type = node
# memoize any annotations
return unless type
memos.types[pathName] = type
if type is ObjectId
memos.oids[pathName] = type
else if type in primitives
memos.primitives[pathName] = type
else if type in natives
memos.natives[pathName] = type
else
memos.annotations[pathName] = type
chain = type.inheritanceChain?()
if chain and Model in chain
isSubcollectionType = path.slice(-1)[0] is '0'
if isSubcollectionType
memos.subcollectionEmbeds[path.slice(0,-1).join '.'] = type
else
memos.embeds[pathName] = type
return # we don't want to implicitly return anything from the above if-ladder
memos
###
@method: property of the constructor.
@signature: Model.getType(model, path)
@param: model - that we're searching
@param: path - that we're searching for
@description: returns the type (the cast function or constructor)
that correlates to the given path of the given model.
@todo: reimplement. for now this will work, but it's a bit ugly,
and it probably performs badly relative to the optimal.
###
@getType = (model, path)->
{constructor} = model
{types} = constructor
return unless types
if type = types[path.join '.']
return type
else
path = path.slice()
tryPath = []
while component = path.shift()
tryPath.push component
if type = types[tryPath.join '.']
ref = type
continue
chain = ref?.inheritanceChain?()
if chain and Model in chain
path.push tryPath.pop()
return Model.getType JsPath.getAt(model.data, tryPath), path
return
###
@method: property of the constructor.
@signature: Model.castValue(value, type)
@param: value - to be cast.
@param: type - for the value to be cast as.
@return: the casted value
###
@castValue = (value, type)->
unless type? then # console.log '[WARN] castValue is called without a type.'
else if type is Object or
type is RegExp or
type in primitives
type value
else if value instanceof type
return value
else if type is ObjectId or type is Date
try
new type value
catch e then debugger
else
chain = type.inheritanceChain?()
if chain and Model in chain
if value instanceof type
value
else
new type value
else if type
throw new TypeError \
"""
Don't know how to cast value of type "#{value.constructor.name}"
to type "#{type}".
"""
###
Querying
@description: see ./find.coffee for detailed explanations.
###
{@one, @all, @some, @someData, @remove, @removeById, @drop, @cursor
@count, @teasers, @hose, @mapReduce, @assure, @update, @each} = require './find'
###
Feeding
@description: see ./feed.coffee
###
{@appendToFeed} = require './feed'
###
@constructor.
@signature: new Model(data)
@param: data - with which to initialize the new instance.å
@description: create a new Model instance.
###
constructor:(data={})->
super data
model = @
ready_ = no
# defineProperty model, 'isReady'
# get :->
# ready_ or= model.getClient().state is 'connected'
defineProperty model, 'isNew',
value : yes
writable : yes
defineProperty model, 'defaults', value: {}
defineProperty model.defaults, 'beenApplied',
value : no
writable : yes
defineProperty model, 'data',
value: {}
enumerable: yes
# allow a maximum of 1 parent to be specified per model
# TODO: perhaps we can introduce multidimensionality, but
# of course it is a logical impossibility when it comes
# to embedding.
parent = null
defineProperty model, 'parent_', writable: yes
# Allow a model to know its path:
defineProperty model, 'path_', writable: yes
# Root node:
defineProperty model, 'rootNode_', writable: yes
defineProperty model, 'isRoot_',
value: yes
writable: yes
# Support embedding models directly:
isEmbedded_ = no
defineProperty model, 'isEmbedded_',
set :(value)-> isEmbedded_ = value
get :-> isEmbedded_
# Support embedding models into "subcollections":
inSubcollection_ = no
defineProperty model, 'inSubcollection_',
set :(value)-> inSubcollection_ = isEmbedded_ = yes
get :-> inSubcollection_
# we need a place to store "setter values"
defineProperty model, 'setterValues', value: {}
for own parentPath, paths of model.constructor.accessorParents
model.defineAccessorsOf parentPath.split('.').slice(1), paths
for prop in model.constructor.rootProperties
defineRootAccessorOf_ model, prop
# import the data, casting values and constructing objects, as appropriate:
model.set data
# initialize any embedded docs.
model.initEmbeds()
###
@function.
@signature: defineRootAccessorOf_(model, propertyName)
@param: model
@param: prop - the property name
###
defineRootAccessorOf_ =(model, prop)->
{data, defaults} = model
unless prop of model
defineProperty model, prop,
enumerable: yes
get :->
if data[prop]?
data[prop]
else
#model.applyDefaults()
data[prop] = defaults[prop]
set :(value)->
data[prop] = value
###
@method.
@signature: Model::defineAccessorsOf(parentPath, paths)
@param: parentPath - an array of the segments of the path
drilling down to, but not including the accessor itself
@param: paths - an array of the complete paths of setters
redundant, but convenient. this may change.
@return: model
@description: returns a structure object that has all
accessors predefined.
###
defineAccessorsOf:(parentPath, paths)->
model = @
{data} = model
unless parentPath.length
parent = data
else
parent = JsPath.getAt(data, parentPath) or {}
JsPath.setAt data, parentPath, parent
for path in paths
assignAccessorsByPath_ model, data, parent, path #^* see below.
@
###
@function.
@signature: assignAccessorsByPath_(model, data, parent, path)^*
@param: model - the instance.
@param: data - the working tree.
@param: parent - the owner of the properties we're setting.
@param: path - the full path of the property we're setting.
@description: a helper function for Model.defineAccessorsOf()
so we don't create functions in the loop. (see above ^*)
###
assignAccessorsByPath_ = (model, data, parent, path)->
pathName = path.join '.'
prop = path.slice(-1)[0]
setter = model.constructor.setters[pathName]
getter = model.constructor.getters[pathName]
defineProperty parent, prop,
enumerable : yes
set :(value)->
if setter
value = setter.call parent, value #^**
model.setterValues[pathName] = value
get :->
value = model.setterValues[pathName]
if getter
value = getter.call parent, value #^**
value
# ** call accessors in the context of the parent so that
# "this" is meaningful.
###
@method.
@signature: Model::applyDefaults()
@param: callback
@return: the model.defaults object
@description: apply all the defaults throughout the model.
call .applyDefaults() on any embedded models encountered
in the walk.
###
applyDefaults:(isDeep=no)->
model = @
if model.defaults? and not model.defaults.beenApplied
# set default values for all fields
for own defaultPath, defaultValue of model.constructor.defaults
if 'function' is typeof defaultValue
defaultValue = defaultValue.call model
JsPath.setAt model.defaults, defaultPath, defaultValue
model.defaults.beenApplied = yes
if isDeep
for own embedPath, embedConstructor of model.constructor.embeds
JsPath.getAt(model, embedPath)?.applyDefaults()
for own subcollectionEmbedPath, subcollectionEmbedAnnotation of model.constructor.subcollectionEmbeds
JsPath.getAt(model, subcollectionEmbedPath)?.forEach (embed)->
embed.applyDefaults()
model
###
@method.
@signature: Model::initEmbeds()
@description: rather a heavy function that will initialize
embedded models and embedded subcollections. Separated this
from .applyDefaults(), because the latter should be fleet.
###
initEmbeds:->
model = @
# initialize any models that are undefined.
for own embedPath, embedConstructor of model.constructor.embeds
embedPath = embedPath.split '.'
unless JsPath.getAt(model.data, embedPath)?
embed = new embedConstructor
embed.path_ = embedPath
embed.parent_ = JsPath.getAt model, embedPath.slice 0, -1
JsPath.setAt model.defaults, embedPath, embed
# initialize any subcollections
for own subcollectionEmbedPath, subcollectionEmbedAnnotation of \
model.constructor.subcollectionEmbeds
subcollectionEmbedPath = subcollectionEmbedPath.split '.'
unless JsPath.getAt(model.data, subcollectionEmbedPath)?
parent = JsPath.getAt model, subcollectionEmbedPath.slice 0, -1
subcollection = new Subcollection \
parent, [], subcollectionEmbedAnnotation
subcollection.path_ = subcollectionEmbedPath
JsPath.setAt model.defaults, subcollectionEmbedPath, subcollection
###
@method.
@signature: Model::validate(callback)
@param: callback
@return: errs — that were encountered in the walk.
@description: validate the data of "this", emitting events.
###
validate:(callback)-> Validator.validate @, callback
@validateAt =(path, value)->
if @paths[path]?
validators = @validators[path]
for {validate} in validators
try success = validate value
catch e then return no
return success
return yes
else return no
###
@constructor.
@signature: Model::getClient()
@returns: client - of the constructor.
###
getClient:->
@constructor.getClient()
###
@constructor.
@signature: Model::getClient()
@returns: collection name - of the constructor.
###
getCollectionName:->
@constructor.getCollectionName()
###
@method.
@signature: Model::save(callback)
@param: callback
@description: save this model to its collection, or notify
its parent that it should be saved, in the case of embedding.
###
save: (callback)->
model = @
model.applyDefaults(model.isRoot_)
model.validate save_0_.bind model, callback
model
#else if isNew
###
@function. bound to the model instance
@signature: save_0_.bind(model, callback)
@param: model - to bind the function to
###
save_0_ =(callback, err)->
model = @
if err?
callback? err
else if model.isRoot_
collection = model.constructor.getCollection()
unless model.data._id?
data = model.get yes
delete data.bongo_
model._id = data._id = new ObjectId
collection.insert data, (safe:yes), save_1_.bind model, callback, yes
else
# TODO: implement atomic updates
data = model.get yes
delete data._id
delete data.bongo_
collection.update \
(_id: do model.getId), data,
(safe:yes), save_1_.bind model, callback, no
else
model.rootNode_?.saveAtomically model, callback
###
@function. bound to the model instance
@signature: save_1_.bind(model, callback)
@param: model - to bind the function to
###
save_1_ =(callback, isNew, err, docs)->
model = @
{constructor} = model
unless err
if id = docs[0]?._id
model.data._id = id
if constructor.feedable is true or constructor.feedable?.call? model
constructor.appendToFeed model, if isNew then 'new' else 'update'
callback?.call model, err, docs, isNew
###
@method.
@signature: Model::saveAtomically(model, callback)
@throws: an schemaError
###
saveAtomically:(model, callback)->
if @notRoot
throw new Error \
"don't call .saveAtomically() on a non-root node."
else
@save callback
#
#getMemoByNameAndPath:(memoName, path)->
# {constructor, data} = @
# path = path.slice()
# memo = constructor[memoName][path.join '.']
# return [] unless memo
# prop = path.pop()
# parent = JsPath.getAt data, path
# [memo, prop, parent]
#
#setSubcollection:(path, array)->
# [annotation, prop, parent] = @getMemoByNameAndPath 'subcollections', path
# subcollection = new Subcollection @, array, annotation
# parent[prop] = subcollection
###
@method.
@signature: Model::set(data)
@param: data - a map of paths to set data to. Use dot notation if you
want to reach into objects, as there is no way to recursively merge JS
objects without astonishing side effects. Object notation "clobbers"
sibling properties.
@description: sets properties to the model by path.
###
set:(data)->
model = @
{constructor} = model
new Traverse(data)
.forEach (node)->
return if not node?
if node.constructor is ObjectId
@update node, yes
if Array.isArray node
type = constructor.subcollections[@path.join '.']
subcollection = new Subcollection model, node, type
@update subcollection
else
if @path.length
type = Model.getType model, @path
if type and type isnt Object
@update Model.castValue(node, type), yes
return
# if @node instanceof Model
# @update @node, yes
# traverse again to set the path
# TODO: try to optimize this so we only need to walk once.
new Traverse(data)
.forEach (node)->
if node instanceof Model
# I am not 100% convinced that this assumption will hold true:
node.isRoot_ = no
node.rootNode_ = model
node.path_ = @path
node.parent_ = @parent.node
@update node
return
#@node
for own path, value of data
JsPath.setAt model.data, path, value
# TODO: this is a bit ugly:
model._id = data._id if data._id
###
@function.
@signature: attachOuterAccessor_(model, path)
@param: model
@param: path - the path (inside data) we want to alias.
@description: helper to add accessors onto the root level
of the model to access the members on the root level of
the model's data object.
###
attachOuterAccessor_ = (model, path)->
defineProperty model, path,
enumerable: yes
get :-> model.data[path]
set :(value)-> model.data[path] = value
shouldBeSaved:(path)->
if path is '_id' then no else console.log path; yes
###
@method.
@signature Model::get()
@description: traverse the model (which implicitly will call
any getters), prune nulls and undefineds, return the results
of the traversal.
###
get:(shouldPrune=no)->
model = @
model.applyDefaults()
data = extend {}, model.defaults, if shouldPrune then model.prune() else model.data
# this will call the getters and return a new object
new Traverse(data).forEach ->
if not @node?
@delete() # remove "undefined" and "null" values
else if @node instanceof Subcollection
@update [].slice.call @node
else
@update @node.get?() or @node
getId:->
# TODO: implement plugins
id = @data._id
if 'string' is typeof id
new ObjectId id
else
id
equals:(model, deep=no)->
unless deep
@getId().equals model?.getId?()
# TODO: I'm not currently interested in "deep", but it might be needed later CT
prune:do ->
applyFilter =(node, constructor, pathName)->
filter = constructor.filters[pathName]
filter node
(isHard=no)->
model = @
# model.applyDefaults()
allowed = []
pruned = []
{constructor} = model
# data = model.get()
method = if isHard then 'forEach' else 'map'
prunedData = new Traverse(model.data)[method] (node)->
pathName = @path.join '.'
# console.log pathName
if node instanceof ObjectId
@update ObjectId(node+''), yes
else if pathName is '_id'
# it's the mongo ObjectId
@update node, yes
else if pathName of constructor.embeds
# it's a directly-embedded doc
@update node.prune(), yes
else if pathName of constructor.subcollectionEmbeds
prunedCollection = (embed.prune(isHard) for embed in node)
# it's a subcollection of embeds
@update prunedCollection, yes
else if pathName of constructor.paths # it's a schematical path
if pathName of constructor.filters # it needs filtered
@update applyFilter(node), yes
else if pathName.length # it's schematical
@update node, yes
else
@update node
else
# never heard of it; pruning!
@remove()
prunedData
updateInstances:(atomically)->
{broadcastChanges} = @constructor
prunedModifier = {}
for own op of atomically
prunedModifier[op] = {}
for own field, val of atomically[op]
unless field in ['snapshot','snapshotIds'] # TODO: this is a one-off hack.
prunedModifier[op][field] = val
if @constructor.getBroadcastable()
@emit 'updateInstance', prunedModifier || @
update:(atomically, callback=->)->
model = @
if 'function' is typeof atomically
callback = atomically
atomically = undefined
unless atomically
Model::save.call model, (err)->
if err
callback err
else
model.updateInstances()
callback null
else
collection = model.constructor.getCollection()
update = _id: model.getId()
for own path, value of atomically
# if /^$/.test path then use$Set = yes
type = Model.getType model, path.split '.'
if type and type isnt Object
value = Model.castValue value, type
atomically[path] = value
new MongoOp(atomically).applyTo(model.data) # first update the one in memory.
collection.update update, atomically, (err)-> # then update the one in the database.
if err
callback err
else
model.updateInstances(atomically)
callback null
remove:(callback)-> @constructor.remove _id: @getId(), callback
['getAt','setAt','deleteAt']
.forEach (method)=> @::[method] =(path)->
JsPath[method].call null, @data, path
###
Footnotes:
1 - ad hoc properties not associated with a schema are fine, but we don't persist them to Mongo.
2 - apply defaults / validations on output (not here).
3 - the human-readable description of the schema, including "type annotations" (JS constructors/primitive casts, really) and validation functions (including some sugared inbuilt ones).
4 - if it has a name, it may be a constructor; this might be botched.
5 - because of overloading, we need to make sure this isn't a field called "validator".
6 - defaults are applied on output.
7 - normal validators only take 1 argument: a value which needs to be validated. There are also a class of so-called "curried" validators that take 2 arguments (e.g. pattern and enum): the first is arbitrarily supplied during schema creation, and the second is the value described above which needs to be validated.
###