Skip to content

Commit

Permalink
Merge pull request #169 from sliit-foss/feat/increase-filter-query-fi…
Browse files Browse the repository at this point in the history
…lter-support

Feat(filter-query): added support for level 2 fitlers
  • Loading branch information
Akalanka47000 authored Mar 25, 2024
2 parents 6fd9f88 + 1656a89 commit 67831b4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 28 deletions.
31 changes: 3 additions & 28 deletions packages/mongoose-filter-query/src/index.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,9 @@
import { mapValue, replaceOperator } from "./utils";

const complexOperators = ["and", "or"];
import { mapFilters } from "./utils";

const mongooseFilterQuery = (req, res, next) => {
try {
if (req.query.filter) {
Object.keys(req.query.filter).forEach((key) => {
const value = req.query.filter[key];
if (complexOperators.includes(key)) {
req.query.filter[`$${key}`] = value.split(",").map((kv) => {
const [key, value] = kv.split("=")
return { [key]: mapValue(value) }
})
delete req.query.filter[key]
} else {
const complexOp = complexOperators.find((op) => value.startsWith(`${op}(`));
if (complexOp) {
const values = replaceOperator(value, complexOp)?.split(",");
req.query.filter[`$${complexOp}`] = values.map((subValue) => ({
[key]: mapValue(subValue)
}));
delete req.query.filter[key];
} else {
req.query.filter[key] = mapValue(value);
}
}
});
} else {
req.query.filter = {};
}
req.query.filter = mapFilters(req.query.filter) ?? {}
mapFilters(req.query.filterl2)
if (req.query.sort) {
Object.keys(req.query.sort).forEach((key) => {
const dir = req.query.sort[key];
Expand Down
29 changes: 29 additions & 0 deletions packages/mongoose-filter-query/src/utils.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const complexOperators = ["and", "or"];

export const replaceOperator = (value, operator) => {
value = value.replace(`${operator}(`, "").slice(0, -1);
if (isNaN(value)) {
Expand Down Expand Up @@ -38,3 +40,30 @@ export const mapValue = (value) => {
}
return value;
};

export const mapFilters = (filter = {}) => {
if (filter) {
Object.keys(filter).forEach((key) => {
const value = filter[key];
if (complexOperators.includes(key)) {
filter[`$${key}`] = value.split(",").map((kv) => {
const [key, value] = kv.split("=")
return { [key]: mapValue(value) }
})
delete filter[key]
} else {
const complexOp = complexOperators.find((op) => value.startsWith(`${op}(`));
if (complexOp) {
const values = replaceOperator(value, complexOp)?.split(",");
filter[`$${complexOp}`] = values.map((subValue) => ({
[key]: mapValue(subValue)
}));
delete filter[key];
} else {
filter[key] = mapValue(value);
}
}
});
}
return filter;
}

0 comments on commit 67831b4

Please sign in to comment.