Created
September 24, 2018 14:26
-
-
Save ivalkenburg/cc9b4fc300e632d34857944137598958 to your computer and use it in GitHub Desktop.
errors.js
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
import Vue from 'vue'; | |
/** | |
* Handles laravel form requests errors. | |
*/ | |
export class FormErrors { | |
constructor() { | |
this.setErrors({}); | |
} | |
/** | |
* Handle error response. | |
* | |
* @param error | |
*/ | |
handle(error) { | |
if (error.response.status !== 422 && error.response.status !== 429) { | |
App.$flash({type: 'error', text: error.response.data.message || error.response.statusText}); | |
} else { | |
this.errors = error.response.data.errors; | |
} | |
} | |
/** | |
* (INTERNAL) Set errors. | |
* | |
* @param {object} errors | |
* @returns {void} | |
*/ | |
setErrors(errors) { | |
this._vm = new Vue({ | |
data() { | |
return { | |
errors: errors | |
} | |
} | |
}); | |
} | |
/** | |
* Returns whether we got any errors for given field. | |
* | |
* @param {string} field | |
* @returns {boolean} | |
*/ | |
has(field) { | |
return typeof this.errors[field] !== 'undefined'; | |
} | |
/** | |
* Returns whether we got any errors. | |
* | |
* @returns {boolean} | |
*/ | |
hasAny() { | |
return Object.keys(this.errors).length > 0; | |
} | |
/** | |
* Get all errors for given field. | |
* | |
* @param {string} field | |
* @returns {Array<string>} | |
*/ | |
get(field) { | |
return this.errors[field] || []; | |
} | |
/** | |
* Returns first error for given field. | |
* | |
* @param {string} field | |
* @returns {string|null} | |
*/ | |
getFirst(field) { | |
if (!this.has(field)) return null; | |
return this.errors[field][0] || null; | |
} | |
/** | |
* Clear error by field. | |
* | |
* @param {string} field | |
*/ | |
clear(field) { | |
if (!this.has(field)) return; | |
Vue.delete(this.errors, field); | |
} | |
/** | |
* Clear all errors. | |
*/ | |
clearAll() { | |
if (!this.hasAny()) return; | |
this.errors = {}; | |
} | |
/** | |
* Returns errors object from vm. | |
* | |
* @returns {object} | |
*/ | |
get errors() { | |
return this._vm.$data.errors; | |
} | |
/** | |
* Sets errors in vm. | |
* | |
* @param {object} errors | |
*/ | |
set errors(errors) { | |
this._vm.$data.errors = errors; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment