Created
September 19, 2018 17:32
-
-
Save vigikaran/c4b92434b3bff8ecf83a49f4704437a3 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
import request from '@/utils/request' | |
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 = {} | |
} | |
} | |
export default class Form { | |
constructor(data) { | |
this.originalData = data | |
for (const field in data) { | |
this[field] = data[field] | |
} | |
this.errors = new Errors() | |
this.submiting = false | |
} | |
data() { | |
const data = {} | |
for (const property in this.originalData) { | |
if (this[property] !== null) { | |
data[property] = this[property] | |
} | |
} | |
return data | |
} | |
reset() { | |
for (const field in this.originalData) { | |
this[field] = this.originalData[field] | |
} | |
this.errors.clear() | |
} | |
post(url) { | |
return this.submit('post', url) | |
} | |
submit(requestType, url) { | |
this.submiting = true | |
return new Promise((resolve, reject) => { | |
request({ | |
url: url, | |
method: requestType, | |
data: this.data() | |
}) | |
.then(response => { | |
this.submiting = false | |
this.onSuccess() | |
resolve(response.data) | |
}) | |
.catch(error => { | |
this.submiting = false | |
this.onFail(error.response.data.error) | |
reject(error.response.data.error) | |
}) | |
}) | |
} | |
onSuccess() { | |
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