Created
July 23, 2019 14:28
-
-
Save FireNeslo/05be18567ba573eaf44c697eb9d8a6e3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function schase(models, objects = {}) { | |
function resolve(data) { | |
for(const [ name, object ] of Object.entries(data)) { | |
const [ _, base, ref ] = /(.*?)(_id|Id|Ids|_ids)?$/.exec(name) | |
const [ plural ] = /es|s$/.exec(ref) || [] | |
const model = base.replace(/es|s$/, '') | |
if(!objects[model]) objects[model] = {} | |
const instances = objects[model] | |
if(ref) { | |
if(plural) { | |
Object.defineProperty(data, model+plural, { | |
get() { | |
return this[name].map(id => instances[id]) | |
} | |
}) | |
} else { | |
Object.defineProperty(data, model, { | |
get() { | |
return instances[this[name]] | |
} | |
}) | |
} | |
} else if(object && typeof object === 'object') { | |
function mapInstance(value) { | |
if(!(value && typeof value === 'object')) return value | |
if(!('id' in value || '_id' in value)) return value | |
const id = value.id || value._id | |
const instance = instances[id] || value | |
instances[id] = Object.assign(value, instance) | |
resolve(value, objects) | |
return instances[id] | |
} | |
data[name] = Array.isArray(object) ? object.map(mapInstance) : mapInstance(object) | |
} | |
} | |
return data | |
} | |
return resolve(models) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment