Last active
March 6, 2017 07:12
-
-
Save BoLaMN/b69979b6dca800fd23579c32900593ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let isPrimitive = function(value) { | |
let primitiveTypes = [ | |
'number', | |
'boolean', | |
'string' | |
]; | |
return (primitiveTypes.indexOf(typeof value) !== -1) || util.isDate(value) || (value === null) || (value.constructor && (value.constructor.name === 'ObjectID')); | |
}; | |
let convertToDotNotation = function(value, modelClass) { | |
if (!value || isPrimitive(value)) { | |
return value; | |
} | |
let obj = {}; | |
var flatten = function(parent, prefix, child) { | |
if (!child) { | |
return; | |
} | |
if (isPrimitive(child)) { | |
if (!parent) { | |
parent = {}; | |
} | |
parent[prefix] = child; | |
return; | |
} | |
let getPrefix = function(key) { | |
if (!prefix) { return key; } else { return prefix + '.' + key; } | |
}; | |
if (Array.isArray(child)) { | |
child.forEach((c, index) => flatten(parent, getPrefix(index), c)); | |
} else { | |
Object.keys(child).forEach(key => flatten(parent, getPrefix(key), child[key])); | |
} | |
}; | |
let { relations } = modelClass.model; | |
Object.keys(relations).forEach(function(relationName) { | |
let { embed, keyFrom } = relations[relationName]; | |
if (embed) { | |
flatten(value, keyFrom, value[keyFrom]); | |
return delete value[keyFrom]; | |
}}); | |
return value; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment