-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongodbQueryParser.js
183 lines (158 loc) · 5.69 KB
/
mongodbQueryParser.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
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
'use strict';
const { ObjectId } = require('mongodb');
const MONGODB_OPERATORS = {
gt: '$gt', // Greater Than
gte: '$gte', // Greater Than or Equal To
lt: '$lt', // Less Than
lte: '$lte', // Less Than or Equal To
ne: '$ne', // Not Equal
eq: '$eq', // Equal
not: '$not', // Not
regexp: '$regex', // Regular Expression
and: '$and', // Logical AND
or: '$or', // Logical OR
nor: '$nor', // Logical NOR
in: '$in', // Inclusion
notIn: '$nin', // Not In
expr: '$expr', // Expression
match: '$match', // Text Search Match
elemMatch: '$elemMatch', // Array Element Match
all: '$all' // All Array Elements Match
};
const parseQueryToJSON = (query) => {
const queryJSONString = decodeURIComponent(query);
return JSON.parse(queryJSONString);
};
const replaceKeyWithMongoDBOperator = (json, key, operator) => {
const value = json[key];
delete json[key];
json[operator] = value;
};
const recursiveKeyReplacement = (json) => {
Object.keys(json).forEach((key) => {
if (key === '_id') {
Object.keys(json[key]).forEach((idKey) => {
if (Array.isArray(json[key][idKey])) {
const objectIds = json[key][idKey].map((id) => new ObjectId(id));
json[key][idKey] = objectIds;
} else {
json[key][idKey] = new ObjectId(json[key][idKey]);
}
});
}
const operator = MONGODB_OPERATORS[key];
if (json[key] !== null && typeof json[key] === 'object') {
if (operator) {
replaceKeyWithMongoDBOperator(json, key, operator);
recursiveKeyReplacement(json[operator]);
} else {
recursiveKeyReplacement(json[key]);
}
} else if (operator) {
replaceKeyWithMongoDBOperator(json, key, operator);
}
});
};
const formatLookupQuery = (query) => {
const as = query?.as || `${query?.model?.charAt(0).toLowerCase() + query?.model?.slice(1)}s`;
return {
$lookup: {
from: `${query?.model?.toLowerCase()}s`,
localField: query?.localField,
foreignField: query?.foreignField,
as,
},
}
}
const extractQueriesFromJSON = (json) => {
const queries = [];
Object.keys(json)?.forEach((key) => {
const value = json[key];
if (value && typeof value === 'object') {
if (key === 'include') {
const lookupQuery = formatLookupQuery(value);
queries.push(lookupQuery);
if (value?.where) {
const matchQuery = { $match: value.where };
queries.push(matchQuery);
}
if (value?.attributes) {
const projectQuery = { $project: value.attributes };
queries.push(projectQuery);
}
if (value?.offset) {
const skipQuery = { $skip: +value.offset };
queries.push(skipQuery);
}
if (value?.limit) {
const limitQuery = { $limit: +value.limit };
queries.push(limitQuery);
}
} else {
queries.push(...extractQueriesFromJSON(value));
}
}
});
return queries;
};
const parseQuery = (req) => {
return new Promise((resolve, reject) => {
console.debug('🚀 ~ Request Query: ', req?.query);
const parsedQuery = [];
try {
const queryHandlers = {
include: (value) => {
const jsonQuery = parseQueryToJSON(value);
recursiveKeyReplacement(jsonQuery);
const includeQueries = extractQueriesFromJSON({ include: jsonQuery });
parsedQuery.push(...includeQueries);
},
query: (value) => {
const query = parseQueryToJSON(value);
recursiveKeyReplacement(query);
return { $match: query };
},
attributes: (value) => {
const attributes = parseQueryToJSON(value);
if (Object.keys(attributes).length === 0) return null;
recursiveKeyReplacement(attributes);
return { $project: attributes };
},
limit: (value) => {
return { $limit: parseInt(value) };
},
offset: (value) => {
return { $skip: parseInt(value) };
},
sort: (value) => {
const sort = parseQueryToJSON(value);
recursiveKeyReplacement(sort);
return { $sort: sort };
}
};
for (const key in req?.query) {
if (queryHandlers[key]) {
const query = queryHandlers[key](req?.query[key]);
if (query) {
parsedQuery.push(query);
}
}
}
if (parsedQuery.length === 0) {
parsedQuery.push({
$match: {}
});
}
console.debug('🚀 ~ Final mongoose query:', parsedQuery);
resolve(parsedQuery);
} catch (error) {
console.error('🚀 ~ Error mongoose query parser: ', error?.message);
reject([
{
msg: error.message
}
]);
}
});
}
module.exports = { parseQuery };