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:
parent
0ae3f0fdfc
commit
fb8eadb4a8
1 changed files with 44 additions and 0 deletions
44
core/server/api/v2/utils/serializers/input/utils/mongo.js
Normal file
44
core/server/api/v2/utils/serializers/input/utils/mongo.js
Normal 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;
|
Loading…
Add table
Reference in a new issue