-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
87 lines (75 loc) · 1.67 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
const _ = require('lodash');
const comparisonOperators = {
equalsTo: '$eq',
greaterThan: '$gt',
greaterThanOrEquals: '$gte',
lessThan: '$lt',
lessThanOrEquals: '$lte',
notEqualTo: '$ne',
in: '$in',
notIn: '$nin',
exists: '$exists',
arrayLength: '$size',
};
const projectionOperators = {
containsElement: '$elemMatch'
};
const logicalOperators = {
and: '$and',
all: '$and',
any: '$or',
or: '$or',
none: '$nor'
};
function map(query) {
query = _.cloneDeep(query);
query = mapQuery(query);
return query
}
function mapQuery(query) {
mapProjection(query);
mapComparisonOperators(query);
mapLogicalOperators(query);
return query;
}
function mapComparisonOperators(query) {
_(query).each((value, key) => {
// go downwards recursively
if (_.isObject(value) && !_.isArray(value) && !_.isDate(value)) {
query[key] = mapQuery(value);
return;
}
for (let op in comparisonOperators) {
if (key === op) {
query[comparisonOperators[op]] = value;
delete query[op];
}
}
});
}
function mapLogicalOperators(query) {
_(query).each((value, key) => {
// go downwards recursively
if (_.isArray(value)) {
for (let op in logicalOperators) {
if (key === op) {
query[logicalOperators[op]] = value;
_(value).each(elem => mapQuery(elem));
delete query[op];
}
}
return;
}
});
}
function mapProjection(query) {
_(query).each((value, key) => {
for(let op in projectionOperators) {
if (key === op) {
query[projectionOperators[op]] = mapQuery(value);
delete query[key];
}
}
});
}
module.exports = map;