This repository was archived by the owner on Aug 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 605
Expand file tree
/
Copy pathmodule.coffee
More file actions
executable file
·553 lines (479 loc) · 17.7 KB
/
module.coffee
File metadata and controls
executable file
·553 lines (479 loc) · 17.7 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
# coffeelint: disable=cyclomatic_complexity
{ Base, Model, ObjectId, Inflector, Register, race, daisy, dash } = require 'bongo'
{ extend, groupBy } = require 'underscore'
cloneDeep = require 'lodash.clonedeep'
Relationship = require './relationship'
Graphlet = require './graphlet'
module.exports = class Module extends Model
@limitEdges = (min, max, args) ->
switch args.length
when 1
[callback] = args
selector = {}
options = { limit: min }
when 2
[selector, callback] = args
options = { limit: min }
when 3
[selector, options, callback] = args
limit = Math.min options.limit ? min, max
if options.targetOptions
options.options ?= {}
options.options.limit = limit
else
options.limit = limit
else
throw new TypeError '''
Module#limitEdges: expected 1, 2 or 3 parameters.
'''
return [selector, options, callback]
@attachInterface = (verb, noun, isPlural, fn) ->
[fn, lowFirstLetter] = [lowFirstLetter, fn] unless fn
name = @getInterfaceName verb, noun, isPlural, yes
this::[name] = fn
return this
@getDefaultRole = -> 'related'
@setRelationships = do ->
needsPopulated = (type) ->
'string' is typeof type or \
Array.isArray(type) and type.filter((item) -> 'string' is typeof item).length
setRelationships = (constructor, relationships) ->
if 'function' is typeof relationships
relationships = relationships.call constructor
constructor.relationships = relationships
for own name, def of relationships
if needsPopulated(def.targetType)
do (def) ->
process.nextTick -> constructor.emit 'needsPopulated', def, 'targetType'
chain = def.inheritanceChain?()
if chain and Module in chain
def = { targetType: def }
def.as or= def.targetType.getDefaultRole()
constructor
.attachInterface('add', name, no, getAdder_ constructor, name, def)
.attachInterface('assure', name, no, getAssurer_ constructor, name, def)
.attachInterface('remove', name, no, getRemover_ constructor, name, def)
.attachInterface('fetch', name, yes, getFetcher_ constructor, name, def)
.attachInterface('fetch', name, no, getFetcher_ constructor, name, def, yes)
.attachInterface('count', name, yes, getCounter_ constructor, name, def)
(relationships) ->
constructor = this
if 'function' is typeof relationships
# when you pass "relationships" as a function, it will be defered until the next tick.
# this can be useful for resolving circular dependencies (a requirement for graphs).
process.nextTick setRelationships.bind null, constructor, relationships
else
setRelationships constructor, relationships
constructor
getOrientation = (def) ->
orientation =
if def.sourceType? then ['source', 'target']
else if def.targetType? then ['target', 'source']
else throw new Error 'Invalid relationship!'
getCounter_ = (constructor, name, def) ->
->
model = this
switch arguments.length
when 1
[callback] = arguments
when 2
[selector, callback] = arguments
when 3
[selector, targetSelector, callback] = arguments
selector ?= {}
selector.as ?=
if 'string' is typeof def.as then def.as
else $in: def.as
orientation = getOrientation(def)
outgoingName = "#{orientation[0]}Name"
outgoingType = "#{orientation[0]}Type"
incomingName = "#{orientation[1]}Name"
incomingId = "#{orientation[1]}Id"
[orientation] = orientation
selector[outgoingName] or= \
if Array.isArray(def[outgoingType])
types = def[outgoingType].map((type) ->
if type.encapsulatedSubclasses?
type.encapsulatedSubclasses.map (subtype) -> subtype.name
else
type.name
)
types = types.reduce ((acc, item) -> (acc).concat item), []
$in: types
else if def[outgoingType].encapsulatedSubclasses?
$in: def[outgoingType].encapsulatedSubclasses.map (type) -> type.name
else
def[outgoingType].name
selector[incomingName] = constructor.name
selector[incomingId] = model.getId()
unless targetSelector
Relationship.count selector, callback
else
Relationship.someData selector, { targetId:1, targetName:1 }, (err, cursor) ->
if err then callback err
else
cursor.toArray (err, docs) ->
if err then callback err
else unless docs?.length then callback null, 0
else
groups = groupBy docs, outgoingName
totalCount = 0
queue = Object.keys(groups).map (constructorName) -> ->
groupedDocs = groups[constructorName]
idSelector = { _id: { $in: (doc.targetId for doc in groupedDocs) } }
extend targetSelector, idSelector
konstructor = Base.constructors[constructorName]
konstructor.count targetSelector, (err, count) ->
if err then queue.fin err
else
totalCount += count
queue.fin()
dash queue, -> callback null, totalCount
getFetcher_ = (constructor, name, def, onlyOne = no) -> ->
limit = 1 if onlyOne
model = this
args = arguments
switch args.length
when 1
[callback] = args
when 2
[selector, callback] = args
when 3
[selector, options, callback] = args
if options.targetOptions
{ options, targetOptions } = options
options or= {}
if 'string' is typeof selector
selector = { as: selector }
selector or= {}
selector.as or=
if 'string' is typeof def.as
then def.as
else $in: def.as
orientation = getOrientation(def)
outgoingName = "#{orientation[0]}Name"
outgoingType = "#{orientation[0]}Type"
incomingName = "#{orientation[1]}Name"
incomingId = "#{orientation[1]}Id"
[orientation] = orientation
selector[outgoingName] or= \
if Array.isArray(def[outgoingType])
types = def[outgoingType].map((type) ->
if type.encapsulatedSubclasses?
type.encapsulatedSubclasses.map (subtype) -> subtype.name
else
type.name
)
types = types.reduce ((acc, item) -> acc.concat item), []
$in: types
else if def[outgoingType].encapsulatedSubclasses?
$in: def[outgoingType].encapsulatedSubclasses.map (type) -> type.name
else
def[outgoingType].name
selector[incomingName] = constructor.name
selector[incomingId] = model.getId()
fields =
'data.flags' : 1
timestamp : 1
idField = "#{orientation}Id"
fields[idField] = 1
fields["#{orientation}Name"] = 1
Relationship.someData selector, fields, options, (err, cursor) ->
return callback err if err
cursor.toArray (err, docs) ->
return callback err if err
unless docs?.length
return callback null, unless limit then []
ordered = {}
docs.forEach (doc, index) ->
ordered[doc[idField]] = index unless ordered[doc[idField]]?
groups = groupBy docs, outgoingName
results = []
targetOptions or= {}
_targetOptions = cloneDeep targetOptions
if targetSelector = _targetOptions.selector or _targetOptions.query
delete _targetOptions.selector
delete _targetOptions.query
else
targetSelector = {}
if _targetOptions.options?
_targetOptions = _targetOptions.options
collectOthers = race (i, type, group, next) ->
ids = (rel[idField] for rel in group)
flags = {}
timestamps = {}
ids.forEach (id, index) ->
flag = group[index].data?.flags
flags[id] = flag if flag
timestamps[id] = group[index].timestamp
Base.constructors[type]
.some extend(targetSelector,
{ _id: { $in: ids } }
), _targetOptions, (err, others) ->
if others?
others = for other in others
other.flags_ = flags[other.getId()]
other.timestamp_ = timestamps[other.getId()]
other
results = results.concat others
next()
, ->
if limit
[results] = results
else if not _targetOptions.sort?
sortedResults = []
results.forEach (result) ->
sortedResults[ordered[result.getId()]] = result
results = sortedResults.filter (value) -> value?
callback null, results
for own type, group of groups
collectOthers type, group
getAdder_ = (constructor, name, def) ->
(target, options, callback) ->
if 'function' is typeof options
callback = options
options = {}
else unless callback
callback = ->
{ targetType, as } = def
if options
if 'string' is typeof options
as = options
else if options.as
{ as } = options
if options.data?
{ data } = options
if Array.isArray as
throw new Error \
'''
You must specify the role when there are multiple options available!
'''
unless target.constructor is targetType or
target.constructor.encapsulatedBy is targetType
if Array.isArray(targetType)
if target.constructor in targetType
targetType = target.constructor
else if target.constructor.encapsulatedBy in targetType
targetType = target.constructor.encapsulatedBy
else
return callback new TypeError 'Type mismatch'
else
return callback new TypeError 'Type mismatch'
rdef = {
targetId : target.getId()
targetName : targetType.name
sourceId : @getId()
sourceName : constructor.name
as
}
if data
rdef.data = data
if target.constructor isnt targetType
rdef.abstractTargetName = targetType.name
rdef.targetName = target.constructor.name
unless target.getId()
callback new Error 'No target id!'
else
new Relationship(rdef).save (err, docs) ->
if err
callback err
else if options?.respondWithCount
delete rdef.targetId
delete rdef.data
Relationship.count rdef, (err, count) ->
if err
callback err
else
callback null, docs, count
else
callback err, docs
getRemover_ = (constructor, name, def) ->
(target, options, callback) ->
[callback, options] = [options, callback] unless callback
{ targetType, as } = def
as = as[0] if Array.isArray as
if options
if 'string' is typeof options
as = options
else if options.as
{ as } = options
rdef =
targetId : target.getId()
targetName : targetType.name
sourceId : @getId()
sourceName : constructor.name
unless as is '*'
rdef.as = as
# TODO: I am implementing a hack here for the time being. Fix for real.
Object.keys(rdef).forEach (key) ->
delete rdef[key] unless rdef[key]?
# TODO: end dirty hack
Relationship.remove rdef,
unless options?.respondWithCount
callback
else ->
delete rdef.targetId
Relationship.count rdef, callback
getAssurer_ = do ->
addIt = (context, adder, target, options, callback) ->
context[adder] target, options, (err) ->
if err
callback err
else
callback null, target
(constructor, name, def) ->
(target, options, callback) ->
[callback, options] = [options, callback] unless callback
[target, callback] = [callback, target] unless callback
options ?= {}
fetcher = @getInterfaceName 'fetch', name
adder = @getInterfaceName 'add', name
selector =
if target?
targetId : target.getId()
as : options?.as
else {}
@[fetcher] selector, (err, module) =>
if err
callback err
else unless def.targetType
callback new Error 'No target type!'
else if module
# update the timestamp on this relationship to reflect the
# fact that it is being assured again, so the timestamp always
# shows the most recent
Relationship.update {
targetId : target.getId()
sourceId : @getId()
as : def.as
}, { $set: { timestamp: new Date } }, (err) ->
callback null, module
else if target
addIt this, adder, target, options, callback
else
target = new def.targetType
target.save (err) =>
if err
callback err
else
addIt this, adder, target, options, callback
remove_ = @::remove
remove:(callback = ->) ->
id = @getId()
Relationship.remove { $or: [{ sourceId: id }, { targetId: id }] }, (err, rels) =>
return callback err if err
remove_.call this, callback
beginGraphlet: -> new Graphlet { nodes: [this] }
getFlag = (key, val) ->
flag = {}
flag["data.flags.#{key}"] = val
flag
getAs = (as) ->
if Array.isArray as then $in: as else as
updateFlag = (sourceId, targetId, as, flag, callback) ->
Relationship.update { targetId, sourceId, as }, flag, callback
unflag:(key, sourceId, as, callback = ->) ->
flag = { $unset: getFlag key, 1 }
updateFlag sourceId, @getId(), getAs(as), flag, callback
flag:(key, val, sourceId, as, callback = ->) ->
flag = { $set: getFlag key, val }
updateFlag sourceId, @getId(), getAs(as), flag, callback
save:(callback) ->
Model::save.call this, callback
parseTargetOptions = (options = {}) ->
if selector = options.selector or options.query
delete options.selector
delete options.query
else
selector = {}
{ options, selector }
collectOthers = (orientation, as, options, onlyOne, callback, err, cursor) ->
idField = "#{orientation}Id"
nameField = "#{orientation}Name"
if err then callback err
else cursor.toArray (err, docs) ->
if err then callback err
else
ordered = {}
docs.forEach (doc, index) ->
id = doc[idField]
ordered[id] = index unless ordered[id]?
groups = groupBy(docs, nameField)
{ options, selector } = parseTargetOptions(options)
results = []
queue = for own type, group of groups
->
flags = {}
ids = group.map (rel, index) ->
id = rel[idField]
flag = rel.data?.flags
flags[id] = flag if flag
id
selector = extend selector, { _id: { $in: ids } }
otherConstructor = Base.constructors[type]
otherConstructor.some selector, options, (err, others) ->
others = others.map (other) ->
other.flags_ = flags[other.getId()]
other
results = results.concat others
queue.fin()
dash queue, ->
if onlyOne
[results] = results
else
sortedResults = []
results.forEach (result) ->
sortedResults[ordered[result.getId()]] = result
results = sortedResults.filter (value) -> value?
callback null, results
filterRelatedIds:(ids, as, orientation, callback) ->
[callback, orientation] = [orientation, callback] unless callback
selector = { as }
id = @getId()
search = if Array.isArray ids then $in: ids else ids
if orientation is 'source'
selector.targetId = search
selector.sourceId = id
else
selector.sourceId = search
selector.targetId = id
Relationship.someData selector, { sourceId:1 }, (err, cursor) ->
if err then callback err
else
cursor.toArray (err, docs) ->
if err
callback err
else
callback null, (doc.sourceId for doc in docs)
fetch:(orientation, name, as, options, callback) ->
[callback, options] = [options, callback] unless callback
currentPosition = switch orientation
when 'target' then 'source'
when 'source' then 'target'
options ?= {}
callback ?= ->
if options.targetOptions?
{ options, targetOptions } = options
onlyOne = options.onlyOne ? no
options.limit = 1 if onlyOne
edgeSelector = if Array.isArray(as) then { as: { $in:as } } else { as }
edgeSelector["#{orientation}Name"] = name
edgeSelector["#{currentPosition}Name"] = @constructor.name
edgeSelector["#{currentPosition}Id"] = @getId()
fields = {}
fields["#{orientation}Id"] = 1
fields["#{orientation}Name"] = 1
fields['data.flags'] = 1
Relationship.someData edgeSelector, fields, options, collectOthers.bind(
this, orientation, as, targetOptions, onlyOne, callback
)
hasTarget: (target, as, callback) ->
Relationship.count {
targetName : target.constructor.name
targetId : target.getId()
sourceId : @getId()
sourceName : @constructor.name
as
}, (err, count) ->
return callback err if err
callback null, count >= 0