Skip to content

Instantly share code, notes, and snippets.

@m4tlch
Forked from lorisleiva/Model.js
Created December 26, 2021 13:09
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 m4tlch/e1baca6121292c14ce25b613bb4ba6bc to your computer and use it in GitHub Desktop.
Save m4tlch/e1baca6121292c14ce25b613bb4ba6bc 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