Skip to content

Instantly share code, notes, and snippets.

@FireNeslo
Created July 23, 2019 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FireNeslo/05be18567ba573eaf44c697eb9d8a6e3 to your computer and use it in GitHub Desktop.
Save FireNeslo/05be18567ba573eaf44c697eb9d8a6e3 to your computer and use it in GitHub Desktop.
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