File: D:/HostingSpaces/SBogers10/farmfun.komma.pro/resources/js/global/models/errorResponse.js
/**
* A laravel error response
*/
class ErrorResponse {
constructor()
{
this._message = '';
this._errors = {};
}
/**
* @param {string} json
* @return {ErrorResponse|null}
*/
static fromJsonString(json) {
if(!this.is(json)) {
return null;
}
let jsonObject = JSON.parse(json);
let instance = new this;
instance._message = jsonObject.message;
instance._errors = jsonObject.errors;
return instance;
}
/**
* Checks that the given json string represents a ErrorResponse
*
* @param {string} json
* @param {boolean} logErrors
* @return {boolean}
*/
static is(json, logErrors = true)
{
let jsonObject = null;
try {
jsonObject = JSON.parse(json);
if(!jsonObject) return false;
} catch (e) {
if(logErrors) console.error('ErrorResponse: The given json does not represent a valid ErrorResponse since the json string was not a valid json');
return false;
}
if(!jsonObject.hasOwnProperty('message') || typeof jsonObject.message !== 'string') {
if(logErrors) console.error('ErrorResponse: The response object must have an message property that is a string. Object:', jsonObject);
return false;
}
if(!jsonObject.hasOwnProperty('errors') || typeof jsonObject.errors !== 'object') {
if(logErrors) console.error('ErrorResponse: The response object must have an errors object that represents valid laravel field errors. Object:', jsonObject);
return false;
}
for(let fieldName in jsonObject.errors) {
if(jsonObject.errors.hasOwnProperty(fieldName) && !Array.isArray(jsonObject.errors[fieldName])) {
if(logErrors) console.error('ErrorResponse: The property "'+fieldName+'" in the errors array must have have array as value containing errors strings. Object:', jsonObject);
return false;
}
}
return true;
}
/**
* Retrurns a comprehensive error message for all the fields.
*
* @return {string}
*/
get message() {
return this._message;
}
/**
* @return {Object} returns an object where the property are field names. and the values are arrays containing errors for those field names.
*/
get errors() {
return this._errors;
}
}
export { ErrorResponse }