simple-body-validator
Version:
This package is inspired by Laravel validation, and aims to make body validation easier for Javascript developers
132 lines (131 loc) • 3.7 kB
JavaScript
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
class ErrorBag {
constructor(errors = {}, messages = {}, firstMessage = '', withErrorTypes = false) {
/**
* All of the registered messages.
*/
this.errors = {};
/**
* All Messages
*/
this.messages = {};
/**
* Stores the first error message
*/
this.firstMessage = '';
/**
* Specify whether error types should be returned or no
*/
this.withErrorTypes = false;
this.errors = errors;
this.messages = messages;
this.firstMessage = firstMessage;
this.withErrorTypes = withErrorTypes;
}
/**
* Set withErrorTypes attribute to true
*/
addErrorTypes() {
this.withErrorTypes = true;
return this;
}
/**
* Add new recodrs to the errors and messages objects
*/
add(key, error) {
if (Array.isArray(this.errors[key]) && Array.isArray(this.messages[key])) {
this.errors[key].push(error);
this.messages[key].push(error.message);
}
else {
this.errors[key] = [error];
this.messages[key] = [error.message];
}
this.firstMessage = this.firstMessage || error.message;
}
;
/**
* Get the first error related to a specific key
*/
first(key = null) {
if (!key) {
return this.firstMessage;
}
if (this.has(key)) {
return this.messages[key][0];
}
return '';
}
;
/**
* Get the error messages keys
*/
keys() {
return Object.keys(this.messages);
}
;
/**
* Get all the messages related to a specific key
*/
get(key, withErrorTypes = this.withErrorTypes) {
if (!this.has(key)) {
return [];
}
if (withErrorTypes) {
return this.errors[key];
}
return this.messages[key];
}
;
/**
* Check if key exists in messages
*/
has(key) {
return this.messages[key] && this.messages[key].length > 0 ? true : false;
}
;
/**
* Get all error messages
*/
all(allMessages = true, withErrorTypes = this.withErrorTypes) {
let messages = withErrorTypes ? Object.assign({}, this.errors) : Object.assign({}, this.messages);
if (!allMessages) {
Object.keys(messages).map(attribute => messages[attribute] = messages[attribute][0]);
}
return messages;
}
;
/**
* Remove error messages
*/
clear(keys) {
// if keys array is emppty - remove all error messages
if (keys.length === 0) {
this.errors = {};
this.messages = {};
this.firstMessage = '';
return this;
}
// Remove error messages for each key
keys.forEach(key => {
if (this.messages.hasOwnProperty(key)) {
delete this.messages[key];
delete this.errors[key];
}
});
this.firstMessage = '';
if (this.keys().length > 0) {
this.firstMessage = this.messages[Object.keys(this.messages)[0]][0];
}
return this;
}
;
/**
* Clone ErrorBag Instance
*/
clone() {
return new ErrorBag(Object.assign({}, this.errors), Object.assign({}, this.messages), this.firstMessage, this.withErrorTypes);
}
}
exports.default = ErrorBag;