Skip to content

Instantly share code, notes, and snippets.

@lorisleiva
Created July 22, 2020 10:32
Show Gist options
  • Save lorisleiva/93e66ba226ec53cc13c9e54d7f334f2c to your computer and use it in GitHub Desktop.
Save lorisleiva/93e66ba226ec53cc13c9e54d7f334f2c to your computer and use it in GitHub Desktop.
// resources/js/models/Model.js
export default class Model {
constructor (attributes = {}) {
this.fill(attributes)
}
static make (attributes = {}) {
return Array.isArray(attributes)
? attributes.map(nested => new this(nested))
: new this(attributes)
}
fill (attributes = {}) {
this.setAttributes(attributes)
this.wrapRelationships()
return this
}
setAttributes (attributes) {
Object.assign(this, attributes)
}
getAttributes () {
return { ...this }
}
clone () {
return this.constructor.make({ ...this.getAttributes() })
}
wrapRelationships () {
let attributes = this.getAttributes() || {}
let relationships = this.getRelationships() || {}
Object.keys(relationships).forEach(key => {
if (attributes.hasOwnProperty(key) && attributes[key]) {
attributes[key] = relationships[key].make(attributes[key])
}
})
this.setAttributes(attributes)
}
getRelationships () {
return {}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment