-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcacheField.js
43 lines (35 loc) · 1.28 KB
/
cacheField.js
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
import _ from 'lodash'
import {addMigration} from './migrations.js'
Mongo.Collection.prototype.cacheField = function(options) {
check(options, {
cacheField:String,
fields:[String],
transform:Match.Optional(Function),
bypassSchema:Match.Optional(Boolean)
})
let collection = options.bypassSchema && Package['aldeed:collection2'] ? this._collection : this
let cacheField = options.cacheField
let fields = options.fields
let topFields = _.uniq(_.map(fields, field => field.split('.')[0]))
let transform = options.transform
if(!transform) {
transform = function(doc) {
return _.compact(_.map(fields, field => _.get(doc, field))).join(', ')
}
}
if(_.includes(topFields, cacheField.split(/[.:]/)[0])){
throw new Error('watching the cacheField for changes would cause an infinite loop')
}
function insertHook(userid, doc){
collection.update(doc._id, {$set:{[cacheField]:transform(_.pick(doc, fields))}})
}
addMigration(collection, insertHook, options)
collection.after.insert(insertHook)
collection.after.update((userId, doc, changedFields) => {
if(_.intersection(changedFields, topFields).length){
Meteor.defer(()=>{
collection.update(doc._id, {$set:{[cacheField]:transform(_.pick(doc, fields))}})
})
}
})
}