Skip to content

Instantly share code, notes, and snippets.

@lorisleiva
Created July 22, 2020 10:13
Show Gist options
  • Save lorisleiva/4c03fc332cd54941493e70ad464f730e to your computer and use it in GitHub Desktop.
Save lorisleiva/4c03fc332cd54941493e70ad464f730e to your computer and use it in GitHub Desktop.
// resources/js/services/Form.js
import FormErrors from './FormErrors'
export default class {
constructor (initialData = {}, submitCallback = null) {
this._initialData = initialData
this._submitCallback = submitCallback
this.errors = new FormErrors()
this.reset()
}
reset () {
this.busy = false
this.successful = false
this.errors.clear()
Object.assign(this, this._initialData)
}
async submit (...args) {
if (this.busy || ! this._submitCallback) {
return
}
this.beforeStart()
const result = await this._submitCallback(this, ...args).catch(error => {
this.onFailure(error)
throw error
})
this.onSuccess()
return result
}
export () {
return { ...this }
}
beforeStart () {
this.busy = true
this.successful = false
this.errors.clear()
}
onSuccess () {
this.busy = false
this.successful = true
}
onFailure (error) {
this.busy = false
if (error.response && error.response.data) {
const { errors, message } = error.response.data
this.setErrors(errors, message)
}
}
setErrors (errors, message) {
this.errors.set(errors, message)
}
}
// resources/js/services/FormErrors.js
export default class {
constructor () {
this.errors = {}
this.message = null
}
set (errors, message) {
this.errors = errors || {};
this.message = message || null;
}
has (field) {
return Object.keys(this.errors).includes(field)
}
get (field) {
if (this.has(field)) {
const error = this.errors[field]
return Array.isArray(error) && error.length > 0 ? error[0] : error
}
}
clear (field) {
if (field) {
Vue.delete(this.errors, field);
} else {
this.errors = {}
this.message = null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment