-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
116 lines (94 loc) · 3.4 KB
/
index.js
File metadata and controls
116 lines (94 loc) · 3.4 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
var variety = require('fs').readFileSync(__dirname +'/lib/variety.js', 'utf8');
var mongo = require('mongodb');
var checkResults = function (collection, expected, callback) {
collection.find().toArray(function (err, data) {
var foundItem, key, type, errors = [], exItem;
while(data.length) {
foundItem = data.pop();
key = foundItem._id.key;
type = foundItem.value.type || foundItem.value.types;
if(key === '_id') {
break;
}
if(typeof type == 'string') {
type = [type];
}
if(typeof expected[key] !== 'undefined') {
// Check that the types are right.
exItem = expected[key];
if(exItem.types) {
for(var i = 0; i < exItem.types.length; i++) {
var extype = exItem.types[i];
if(typeof extype !== 'string') {
exItem.types[i] = varietyTypeOf(extype);
}
}
for(var j = 0; j < type.length; j++) {
var acttype = type[j];
if(exItem.types.indexOf(acttype) == -1){
errors.push('Bad type for key: "'+key+'" - "'+acttype+'" was expecting one of ' + JSON.stringify(exItem.types));
}
}
}
delete expected[key];
} else {
errors.push('Found unexpected key: "' + key + '" of type(s) ' + JSON.stringify(type))
}
}
for (var k in expected) {
if(expected.hasOwnProperty(k)){
exItem = expected[k];
if(typeof exItem.optional === 'undefined' || !exItem.optional){
errors.push('Expected item not found in collection: "'+k + '"');
}
}
}
if(!errors.length) {
errors = null;
}
callback(errors, data);
});
}
var varietyTypeOf = function (thing) {
if(typeof thing === "undefined") {
throw "varietyTypeOf() requires an argument";
}
if(typeof thing !== "object") {
return typeof thing;
} else {
if(thing && thing.constructor === Array) {
return "array";
} else if(thing === null) {
return "null";
} else {
return "object";
}
}
}
module.exports = {
validate:function (collection, expected, callback) {
if(!collection) {
callback(new Error('You must supply a collection'));
return;
}
if(!expected) {
callback(new Error('You must supply an expected schema'));
return;
}
var db = collection.db;
var evalStr = "var collection = '" + collection.collectionName + "'; " + variety;
db.eval(evalStr, function (err, result) {
if(err) {
callback(err, result);
return;
}
// Now load the results
var resultsDB = db.db('varietyResults')
resultsDB.collection(collection.collectionName + 'Keys', function (err, resultsCollection) {
checkResults(resultsCollection, expected, function (err, data) {
callback(err, data);
});
});
});
}
}