0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-03-11 02:12:21 -05:00

Added mongo helper to input serializers

refs #10922

This helper assits in replaces keys and values as defined by the mapping object
This commit is contained in:
Fabien O'Carroll 2019-07-31 14:01:38 +08:00
parent 0ae3f0fdfc
commit fb8eadb4a8

View file

@ -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;