-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcollection-class.js
40 lines (31 loc) · 1.05 KB
/
collection-class.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
import { Mongo } from "meteor/mongo";
import { Meteor } from "meteor/meteor";
/**
*
* @param classDef a constructor function, or an object that defines the type discriminator and corresponding constructors on the form
* {
* discriminatorField: 'fieldName',
* types: {
* "type1": TypeOneConstructor,
* "type2": TypeTwoConstructor
* }
* }
*/
Mongo.Collection.prototype.setClass = function(classDef) {
var self = this;
if (self._transform)
throw new Meteor.Error("Can't setClass on '" +
self._name + "' a transform function already exists!");
let transformFn = function(doc) {
var constructorFn = _.isFunction(classDef)
? classDef
: classDef.types[doc[classDef.discriminatorField]];
const extendedDoc = Object.assign(new constructorFn(), doc);
if (_.isFunction(extendedDoc.collectionClassOnInit)) {
extendedDoc.collectionClassOnInit();
}
return extendedDoc;
};
self._transform = transformFn;
self.toClassInstance = transformFn;
};