Created
October 14, 2015 08:20
-
-
Save FireNeslo/83fb894372f810c23462 to your computer and use it in GitHub Desktop.
Base Mdoel es6
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 belongsto(Class, property, descriptor) { | |
return { | |
get() { | |
return descriptor.get().find(this[property+'Id']) | |
}, | |
set(id) { | |
return this[property+'Id'] = id.id || id | |
} | |
} | |
} | |
function hasOne(Class, property, descriptor) { | |
return { | |
get() { | |
var cache = descriptor.get().cache | |
for(var key in cache) { | |
if(cache[key][property+'Id'] === this.id) { | |
return cache[key] | |
} | |
} | |
}, | |
set(id) { | |
descriptor.get().find(id)[property+'Id'] = this.id | |
} | |
} | |
} | |
function hasMany(Class, property, descriptor) { | |
property = property.replace(/s$/, '') | |
return { | |
get() { | |
var cache = descriptor.get().cache | |
var result = [] | |
for(var key in cache) { | |
if(cache[key][property+'Id'] === this.id) { | |
result.push(cache[key]) | |
} | |
} | |
return result | |
}, | |
set(ids) { | |
ids.map(id => descriptor.get().find(id)[property+'Id']=this.id) | |
} | |
} | |
} | |
const CACHE = Symbol('cache') | |
class Model { | |
static get cache() { | |
return this[CACHE] || (this[CACHE]={}) | |
} | |
static find(id) { | |
return this.cache[id] | |
} | |
@belongsto | |
get model() { | |
return Model | |
} | |
@hasMany | |
get models() { | |
return Model | |
} | |
constructor(data) { | |
Object.assign(this, data) | |
this.constructor.cache[this.id] = this | |
} | |
} | |
var model = new Model({id: 5}) | |
var m = new Model({model: model}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment