forked from coen-hyde/mangomodel
/
index.js
92 lines (77 loc) · 2.24 KB
/
index.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
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
var revalidator = require('revalidator')
, moment = require('moment')
, MonkCollection = require('monk/lib/collection');
var MangoModel = function(db, collection, modelDefinition) {
if (db === null) {
this.getDb = function() {
return MangoModel.globalDb();
}
}
else if (db.hasOwnProperty('driver')) {
this.getDb = function() {
return db;
}
}
else {
// db should be function that returns the actual db connection
this.getDb = db;
}
this.modelDefinition = modelDefinition || {};
this.modelDefinition.collection = collection;
// Copy user defined methods on to model
if (this.modelDefinition.hasOwnProperty('methods')) {
this.methods(this.modelDefinition.methods);
}
};
MangoModel.globalDb = null;
MangoModel.setDb = function(db) {
if (db.hasOwnProperty('driver')) {
this.globalDb = function() {
return db;
}
}
else {
this.globalDb = db;
}
};
MangoModel.models = {};
MangoModel.create = function(db, collection, modelDefinition) {
if (typeof(arguments[0]) === 'string') {
var modelDefinition = collection;
var collection = db;
var db = null;
}
MangoModel.models[collection] = new this(db, collection, modelDefinition);
return MangoModel.models[collection];
};
MangoModel.model = function(collection) {
if (MangoModel.models.hasOwnProperty(collection)) {
return MangoModel.models[collection];
}
}
MangoModel.prototype.methods = function(methods) {
for (var name in methods) {
this[name] = methods[name].bind(this);
}
};
MangoModel.prototype.getCollection = function() {
return this.getDb().get(this.modelDefinition.collection);
};
MangoModel.prototype.validate = function(data) {
var schema = {};
if (this.modelDefinition.hasOwnProperty('schema')) {
schema = this.modelDefinition.schema;
}
return revalidator.validate(data, schema);
};
// Copy across all functionality that Monk has
var collectionMethods = Object.keys(MonkCollection.prototype);
collectionMethods.forEach(function(name) {
MangoModel.prototype[name] = function() {
var args = Array.prototype.slice.call(arguments);
var collection = this.getCollection();
var colFn = collection[name];
return colFn.apply(collection, args);
}
});
module.exports = MangoModel;