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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/*jshint node:true*/
"use strict";
/*!
* Search query helpers
*/
var queryRegex = /^\/(.*)\/([imx]*)$/;
/* Generate a mongoose query operator from a ?query= request parameter */
function createQueryOperator(query) {
var or = {
$or: query.split(" OR ").map(function(orOperand) {
var and = {
$and: orOperand.split(" AND ").map(function(andOperand) {
var colonIndex = andOperand.indexOf(":"),
bangIndex = andOperand.indexOf("!");
if (colonIndex === -1 && bangIndex === -1) {
// Invalid operator, skip
return {};
}
var match = andOperand.match(/^([^!:]+)([!:])(.*)$/);
var field = match[1];
var negate = match[2] === "!";
var value = match[3];
var operator = {};
var op, matches;
matches = value.match(queryRegex);
if (matches) {
op = new RegExp(matches[1], matches[2]);
operator[field] = negate ? { $not: op } : op;
} else {
if (negate) {
// Mongoose does not handle { $not: "value" }
operator[field] = { $nin: [value] };
} else {
operator[field] = value;
}
}
return operator;
}).filter(function(operator) {
return Object.keys(operator).length > 0;
})
};
return and.$and.length === 1 ? and.$and[0] : and;
})
};
return or.$or.length === 1 ? or.$or[0] : or;
}
/* Get property path value in a document or in a plain object */
function getPath(obj, path) {
if (typeof obj.get === "function") {
return obj.get(path);
}
var parts = path.split(".");
while (parts.length) {
if (!obj) {
return;
}
obj = obj[parts.shift()];
}
return obj;
}
/* Match a mongoose query criterion to a document */
function matchQueryCriterion(crit, doc) {
return Object.keys(crit).every(function(path) {
var value = getPath(doc, path) || "",
match = crit[path],
negate = false,
result;
if (typeof match === "string") {
result = value.toString() === match;
} else {
if ("$not" in match) {
negate = true;
match = match.$not;
}
if (match instanceof RegExp) {
result = !!value.toString().match(match);
} else if ("$nin" in match) {
result = match.$nin.indexOf(value) === -1;
} else {
return false;
}
}
return negate ? !result : result;
});
}
/* Match a mongoose query operator to a document */
function matchQueryOperator(operator, doc) {
if ("$or" in operator) {
return operator.$or.some(function(op) {
return matchQueryOperator(op, doc);
});
} else if ("$and" in operator) {
return operator.$and.every(function(op) {
return matchQueryOperator(op, doc);
});
} else if ("$not" in operator) {
return !matchQueryOperator(operator.$not, doc);
} else {
return matchQueryCriterion(operator, doc);
}
}
module.exports = {
create: createQueryOperator,
match: matchQueryOperator
};