Last active
May 31, 2018 13:47
-
-
Save vigikaran/d66721f1c50a83f675190b7e901b44c4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class Errors { | |
constructor() { | |
this.errors = {}; | |
} | |
has(field) { | |
return this.errors.hasOwnProperty(field); | |
} | |
any() { | |
return Object.keys(this.errors).length > 0; | |
} | |
get(field) { | |
if (this.errors[field]) { | |
return this.errors[field][0]; | |
} | |
} | |
record(errors) { | |
this.errors = errors; | |
} | |
clear(field) { | |
if (field) { | |
delete this.errors[field]; | |
return; | |
} | |
this.errors = {}; | |
} | |
} | |
class Form{ | |
constructor(data) { | |
this.originalData = data; | |
for (let field in data) { | |
this[field] = data[field]; | |
} | |
this.errors = new Errors(); | |
} | |
data() { | |
let data = {}; | |
for (let property in this.originalData) { | |
if( this[property] != null){ | |
data[property] = this[property]; | |
} | |
} | |
return data; | |
} | |
reset() { | |
for (let field in this.originalData) { | |
this[field] = this.originalData[field]; | |
} | |
this.errors.clear(); | |
} | |
post(url) { | |
return this.submit('post', url); | |
} | |
submit(requestType, url) { | |
return new Promise((resolve, reject) => { | |
axios[requestType](url, this.data()) | |
.then(response => { | |
this.onSuccess(response.data); | |
resolve(response.data); | |
}) | |
.catch(error => { | |
this.onFail(error.response.data.error); | |
reject(error.response.data.error); | |
}); | |
}); | |
} | |
onSuccess(data) { | |
this.reset(); | |
} | |
onFail(errors) { | |
this.errors.record(errors); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment