Created
July 22, 2020 10:32
-
-
Save lorisleiva/93e66ba226ec53cc13c9e54d7f334f2c to your computer and use it in GitHub Desktop.
This file contains 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
// 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