From aa84e0a082a372ed3df8cbb639d7b4552902d522 Mon Sep 17 00:00:00 2001 From: Perfect Makanju Date: Wed, 17 Jul 2019 16:09:55 +0100 Subject: [PATCH] Prevent escaping on custom condition --- src/index.js | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/index.js b/src/index.js index dff3128..f01c582 100644 --- a/src/index.js +++ b/src/index.js @@ -72,6 +72,18 @@ export const dbTypes = [ const sanitize = identifier => identifier.replace(/([^A-Za-z0-9_]+)/g, ''); +const getCondition = (conditionMapper, column, condition) => { + let currCondition = conditionMap[condition]; + if (conditionMapper) { + const mappedCondition = conditionMapper(column, condition, currCondition); + if (mappedCondition) { + currCondition = mappedCondition; + } + } + + return currCondition; +}; + export const defaultPreprocessor = () => filterKey => `"${sanitize(filterKey)}"`; export const jsonbPreprocessor = jsonbColumn => filterKey => `${sanitize(jsonbColumn)}->>'${sanitize(filterKey)}'`; @@ -105,13 +117,7 @@ const processFilter = (filterQS, castFn, preprocessor, conditionMapper) => { if (cast) query = `(${preprocessed})::${cast}`; } - let currCondition = conditionMap[condition]; - if (conditionMapper) { - const mappedCondition = conditionMapper(column, condition, currCondition); - if (mappedCondition) { - currCondition = mappedCondition; - } - } + let currCondition = getCondition(conditionMapper, column, condition); if (currCondition.includes('??')) { return currCondition.replace('??', query); } @@ -139,7 +145,7 @@ export const knexFlexFilter = (originalQuery, where = {}, opts = {}) => { let value = where[key]; // Escape apostrophes correctly - const matchEscape = conditionMap[condition].match(/'(.*)\?(.*)'/); + const matchEscape = getCondition(conditionMapper, column, condition).match(/'(.*)\?(.*)'/); if (matchEscape) { // eslint-disable-next-line no-unused-vars const [_, pre, post] = matchEscape;