-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathindex.js
61 lines (51 loc) · 1.84 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
module.exports = invokeFilter;
const resolveSchemaDependencies = require("./resolveDependencies");
function invokeFilter(schema, doc) {
const flatSchema = resolveSchemaDependencies(schema, doc);
return filterObjectOnSchema(flatSchema, doc)
}
function filterObjectOnSchema(schema, doc) {
var results;
//console.log("DOC: ", JSON.stringify(doc, null, 2));
//console.log("SCH: ", JSON.stringify(schema, null, 2));
if (schema.type === 'object') {
results = {}; // holds this levels items
// process properties - recursive
Object.keys(schema.properties).forEach(function (key) {
if (typeof (doc[key]) !== 'undefined') {
if (doc[key] === null) {
results[key] = doc[key];
} else {
var sp = schema.properties[key];
if (sp.type === 'object') {
// check if property-less object (free-form)
if (sp.hasOwnProperty('properties')) {
results[key] = filterObjectOnSchema(sp, doc[key]);
} else {
if (Object.keys(doc[key]).length > 0) {
results[key] = doc[key];
}
}
} else if (sp.type === 'array') {
if (doc[key]) results[key] = filterObjectOnSchema(sp, doc[key]);
} else if (sp.type === 'boolean' || sp.type === 'number' || sp.type === 'integer' || sp.type === 'string') {
if (typeof doc[key] !== 'undefined') results[key] = doc[key];
} else {
if (doc[key]) results[key] = doc[key];
}
}
}
});
} else if (schema.type === 'array') {
// arrays can hold objects or literals
if (schema.items.type === 'object') {
results = [];
doc.forEach(function (item) {
results.push(filterObjectOnSchema(schema.items, item));
});
} else {
results = doc;
}
}
return results;
}