1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | module.exports = class ErrorMap {
|
7 |
|
8 | _data = {};
|
9 |
|
10 | has (key) {
|
11 | return key ? Object.prototype.hasOwnProperty.call(this._data, key)
|
12 | : Object.values(this._data).length > 0;
|
13 | }
|
14 |
|
15 | get (key) {
|
16 | return Object.prototype.hasOwnProperty.call(this._data, key) ? this._data[key] : [];
|
17 | }
|
18 |
|
19 |
|
20 | getFirst (key) {
|
21 | if (key) {
|
22 | return this.has(key) ? this._data[key][0] : '';
|
23 | }
|
24 | for (const items of Object.values(this._data)) {
|
25 | if (items.length) {
|
26 | return items[0];
|
27 | }
|
28 | }
|
29 | return '';
|
30 | }
|
31 |
|
32 | getAllFirst () {
|
33 | const result = {};
|
34 | for (const key of Object.keys(this._data)) {
|
35 | if (this._data[key].length) {
|
36 | result[key] = this._data[key][0];
|
37 | }
|
38 | }
|
39 | return result;
|
40 | }
|
41 |
|
42 | add (key, error) {
|
43 | if (!error) {
|
44 | return this;
|
45 | }
|
46 | if (Array.isArray(this._data[key])) {
|
47 | this._data[key].push(error);
|
48 | } else {
|
49 | this._data[key] = [error];
|
50 | }
|
51 | return this;
|
52 | }
|
53 |
|
54 | assign (data) {
|
55 | if (!data) {
|
56 | return this;
|
57 | }
|
58 | for (const key of Object.keys(data)) {
|
59 | if (Array.isArray(data[key])) {
|
60 | for (const value of data[key]) {
|
61 | this.add(key, value);
|
62 | }
|
63 | } else {
|
64 | this.add(key, data[key]);
|
65 | }
|
66 | }
|
67 | return this;
|
68 | }
|
69 |
|
70 | clear (key) {
|
71 | if (key) {
|
72 | delete this._data[key];
|
73 | } else {
|
74 | this._data = {};
|
75 | }
|
76 | return this;
|
77 | }
|
78 | }; |
\ | No newline at end of file |