Skip to content

Instantly share code, notes, and snippets.

@FireNeslo
Created October 14, 2015 08:20
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/83fb894372f810c23462 to your computer and use it in GitHub Desktop.
Save FireNeslo/83fb894372f810c23462 to your computer and use it in GitHub Desktop.
Base Mdoel es6
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