From 1656a8996f54fec5f75e749fdffa59dee8787298 Mon Sep 17 00:00:00 2001 From: Akalanka Perera Date: Mon, 25 Mar 2024 14:53:50 +0000 Subject: [PATCH] Feat(filter-query): added support for level 2 fitlers --- packages/mongoose-filter-query/src/index.js | 31 ++------------------- packages/mongoose-filter-query/src/utils.js | 29 +++++++++++++++++++ 2 files changed, 32 insertions(+), 28 deletions(-) diff --git a/packages/mongoose-filter-query/src/index.js b/packages/mongoose-filter-query/src/index.js index e94afd9..f99c22f 100644 --- a/packages/mongoose-filter-query/src/index.js +++ b/packages/mongoose-filter-query/src/index.js @@ -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]; diff --git a/packages/mongoose-filter-query/src/utils.js b/packages/mongoose-filter-query/src/utils.js index cbddc05..45e9e46 100644 --- a/packages/mongoose-filter-query/src/utils.js +++ b/packages/mongoose-filter-query/src/utils.js @@ -1,3 +1,5 @@ +const complexOperators = ["and", "or"]; + export const replaceOperator = (value, operator) => { value = value.replace(`${operator}(`, "").slice(0, -1); if (isNaN(value)) { @@ -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; +} \ No newline at end of file