Skip to content

Instantly share code, notes, and snippets.

@lorisleiva

lorisleiva/Model.js

Created Jul 22, 2020
Embed
What would you like to do?
// 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
You can’t perform that action at this time.