From fb8eadb4a8109ba987d79decfe331c669a446609 Mon Sep 17 00:00:00 2001 From: Fabien O'Carroll Date: Wed, 31 Jul 2019 14:01:38 +0800 Subject: [PATCH] Added mongo helper to input serializers refs #10922 This helper assits in replaces keys and values as defined by the mapping object --- .../v2/utils/serializers/input/utils/mongo.js | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 core/server/api/v2/utils/serializers/input/utils/mongo.js diff --git a/core/server/api/v2/utils/serializers/input/utils/mongo.js b/core/server/api/v2/utils/serializers/input/utils/mongo.js new file mode 100644 index 0000000000..6389d065cf --- /dev/null +++ b/core/server/api/v2/utils/serializers/input/utils/mongo.js @@ -0,0 +1,44 @@ +const _ = require('lodash'); +const nql = require('@nexes/nql'); + +/* + * Returns the replacement value for input, or input if it doesn't exist + */ +function replaceValue(input, valueMappings) { + const replacer = valueMappings.find(({from}) => from === input); + return replacer && replacer.to || input; +} + +function fmap(item, fn) { + return Array.isArray(item) ? item.map(fn) : fn(item); +} + +function mapKeysAndValues(input, mapping) { + return nql.utils.mapQuery(input, function (value, key) { + // Ignore everything that has nothing to do with our mapping + if (key !== mapping.key.from) { + return { + [key]: value + }; + } + + // key: valueA + if (typeof value !== 'object') { + return { + [mapping.key.to]: replaceValue(value, mapping.values) + }; + } + + // key: { "$in": ['valueA', 'valueB'] } + // key: { "$ne": 'valueA' } + return { + [mapping.key.to]: _.reduce(value, (memo, objValue, objKey) => { + return Object.assign(memo, { + [objKey]: fmap(objValue, item => replaceValue(item, mapping.values)) + }); + }, {}) + }; + }); +} + +module.exports.mapKeysAndValues = mapKeysAndValues;