@sugo/mongodb-queryparams
Version:
Unique Queryparams sintax (Inspired in Elastic Search) that creates queries for MongoDB
81 lines • 2.79 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const OPERATORS = ['$and', '$or'];
const mongodb_1 = require("mongodb");
exports.isObject = (item) => item && typeof item === 'object' && !Array.isArray(item) && !(item instanceof Date) && !(item instanceof RegExp);
exports.mergeDeep = (target, ...sources) => {
if (!sources.length) {
return target;
}
const source = sources.shift();
if (exports.isObject(target) && exports.isObject(source)) {
for (const key in source) {
if (exports.isObject(source[key])) {
if (!target[key]) {
Object.assign(target, { [key]: {} });
}
exports.mergeDeep(target[key], source[key]);
}
else {
Object.assign(target, { [key]: source[key] });
}
}
}
return exports.mergeDeep(target, ...sources);
};
exports.cleanQuery = (doc) => {
for (const key in doc) {
if (doc.hasOwnProperty(key)) {
const value = doc[key];
if ('$and' === key) {
for (const subdoc of value) {
doc = exports.mergeDeep(doc, exports.cleanQuery(subdoc));
}
delete doc[key];
}
else if ('$or' === key) {
doc[key] = value.map(v => exports.cleanQuery(v));
}
}
}
return doc;
};
exports.objectToDotNotation = (obj, current, res = {}) => {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
const newKey = current ? current + '.' + key : key;
if (value && typeof value === 'object') {
exports.objectToDotNotation(value, newKey, res);
}
else {
res[newKey] = value;
}
}
}
return res;
};
exports.parseObjectIds = (input) => {
if (typeof input === 'string' && mongodb_1.ObjectId.isValid(input)) {
return new mongodb_1.ObjectId(input);
}
if (typeof input !== 'object' && !Array.isArray(input)) {
return input;
}
for (const key in input) {
if (input.hasOwnProperty(key)) {
const value = input[key];
if (typeof value === 'string' && mongodb_1.ObjectId.isValid(value)) {
input[key] = new mongodb_1.ObjectId(value);
}
else if (Array.isArray(value)) {
input[key] = value.map(v => exports.parseObjectIds(v));
}
else if (typeof value === 'object' && !(value instanceof RegExp)) {
input[key] = exports.parseObjectIds(value);
}
}
}
return input;
};
//# sourceMappingURL=utils.js.map