/
validation-error.ts
257 lines (216 loc) · 7.42 KB
/
validation-error.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import type { Model } from '../..';
import type { ErrorOptions } from './base-error';
import BaseError from './base-error';
/**
* An enum that is used internally by the `ValidationErrorItem` class
* that maps current `type` strings (as given to ValidationErrorItem.constructor()) to
* our new `origin` values.
*/
export enum ValidationErrorItemType {
'notnull violation' = 'CORE',
'string violation' = 'CORE',
'unique violation' = 'DB',
'validation error' = 'FUNCTION',
}
/**
* An enum that defines valid ValidationErrorItem `origin` values
*/
export enum ValidationErrorItemOrigin {
/**
* specifies errors that originate from the sequelize "core"
*/
CORE = 'CORE',
/**
* specifies validation errors that originate from the storage engine
*/
DB = 'DB',
/**
* specifies validation errors that originate from validator functions (both built-in and custom) defined for a given attribute
*/
FUNCTION = 'FUNCTION',
}
/**
* Validation Error Item
* Instances of this class are included in the `ValidationError.errors` property.
*/
export class ValidationErrorItem {
/**
* @deprecated Will be removed in v7
*/
static TypeStringMap = ValidationErrorItemType;
/**
* @deprecated Will be removed in v7
*/
static Origins = ValidationErrorItemOrigin;
/**
* An error message
*/
readonly message: string;
/**
* The type/origin of the validation error
*/
readonly type: keyof typeof ValidationErrorItemType | null;
/**
* The field that triggered the validation error
*/
readonly path: string | null;
/**
* The value that generated the error
*/
readonly value: string | null;
readonly origin: keyof typeof ValidationErrorItemOrigin | null;
/**
* The DAO instance that caused the validation error
*/
readonly instance: Model | null;
/**
* A validation "key", used for identification
*/
readonly validatorKey: string | null;
/**
* Property name of the BUILT-IN validator function that caused the validation error (e.g. "in" or "len"), if applicable
*/
readonly validatorName: string | null;
/**
* Parameters used with the BUILT-IN validator function, if applicable
*/
readonly validatorArgs: unknown[];
/**
* Creates a new ValidationError item. Instances of this class are included in the `ValidationError.errors` property.
*
* @param message An error message
* @param type The type/origin of the validation error
* @param path The field that triggered the validation error
* @param value The value that generated the error
* @param instance the DAO instance that caused the validation error
* @param validatorKey a validation "key", used for identification
* @param fnName property name of the BUILT-IN validator function that caused the validation error (e.g. "in" or "len"), if applicable
* @param fnArgs parameters used with the BUILT-IN validator function, if applicable
*/
constructor(
message: string,
type:
| keyof typeof ValidationErrorItemType
| keyof typeof ValidationErrorItemOrigin,
path: string,
value: string,
instance: Model,
validatorKey: string,
fnName: string,
fnArgs: unknown[],
) {
this.message = message || '';
this.type = null;
this.path = path || null;
this.value = value !== undefined ? value : null;
this.origin = null;
this.instance = instance || null;
this.validatorKey = validatorKey || null;
this.validatorName = fnName || null;
this.validatorArgs = fnArgs || [];
if (type) {
if (this.isValidationErrorItemOrigin(type)) {
this.origin = type;
} else {
const lowercaseType = this.normalizeString(type);
const realType = ValidationErrorItemType[lowercaseType];
if (realType && ValidationErrorItemOrigin[realType]) {
this.origin = realType;
this.type = type;
}
}
}
// This doesn't need captureStackTrace because it's not a subclass of Error
}
private isValidationErrorItemOrigin(
origin:
| keyof typeof ValidationErrorItemOrigin
| keyof typeof ValidationErrorItemType,
): origin is keyof typeof ValidationErrorItemOrigin {
return (
ValidationErrorItemOrigin[
origin as keyof typeof ValidationErrorItemOrigin
] !== undefined
);
}
private normalizeString<T extends string>(str: T): T {
return str.toLowerCase().trim() as T;
}
/**
* return a lowercase, trimmed string "key" that identifies the validator.
*
* Note: the string will be empty if the instance has neither a valid `validatorKey` property nor a valid `validatorName` property
*
* @param useTypeAsNS controls whether the returned value is "namespace",
* this parameter is ignored if the validator's `type` is not one of ValidationErrorItem.Origins
* @param NSSeparator a separator string for concatenating the namespace, must be not be empty,
* defaults to "." (fullstop). only used and validated if useTypeAsNS is TRUE.
* @throws {Error} thrown if NSSeparator is found to be invalid.
*/
getValidatorKey(useTypeAsNS: boolean, NSSeparator: string): string {
const useTANS = useTypeAsNS === undefined || Boolean(useTypeAsNS);
const NSSep = NSSeparator === undefined ? '.' : NSSeparator;
const type = this.origin;
const key = this.validatorKey || this.validatorName;
const useNS = useTANS && type && ValidationErrorItemOrigin[type];
if (useNS && (typeof NSSep !== 'string' || NSSep.length === 0)) {
throw new Error('Invalid namespace separator given, must be a non-empty string');
}
if (!(typeof key === 'string' && key.length > 0)) {
return '';
}
return (useNS ? [this.origin, key].join(NSSep) : key).toLowerCase().trim();
}
}
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param message Error message
* @param errors Array of ValidationErrorItem objects describing the validation errors
*/
class ValidationError extends BaseError {
/** Array of ValidationErrorItem objects describing the validation errors */
readonly errors: ValidationErrorItem[];
constructor(
message: string,
errors: ValidationErrorItem[],
options: ErrorOptions = {},
) {
super(message);
this.name = 'SequelizeValidationError';
this.errors = errors || [];
// Use provided error message if available...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors
.map(
(err: ValidationErrorItem) => `${err.type || err.origin}: ${err.message}`,
)
.join(',\n');
}
// Allow overriding the stack if the original stacktrace is uninformative
if (options.stack) {
this.stack = options.stack;
}
}
/**
* Gets all validation error items for the path / field specified.
*
* @param path The path to be checked for error items
*
* @returns Validation error items for the specified path
*/
get(path: string): ValidationErrorItem[] {
const out: ValidationErrorItem[] = [];
for (const error of this.errors) {
if (error.path === path) {
out.push(error);
}
}
return out;
}
}
export default ValidationError;