UNPKG

1.94 kBJavaScriptView Raw
1/**
2 * Validation error description.
3 */
4export class ValidationError {
5 /**
6 *
7 * @param shouldDecorate decorate the message with ANSI formatter escape codes for better readability
8 * @param hasParent true when the error is a child of an another one
9 * @param parentPath path as string to the parent of this property
10 */
11 toString(shouldDecorate = false, hasParent = false, parentPath = ``) {
12 const boldStart = shouldDecorate ? `\x1b[1m` : ``;
13 const boldEnd = shouldDecorate ? `\x1b[22m` : ``;
14 const propConstraintFailed = (propertyName) => ` - property ${boldStart}${parentPath}${propertyName}${boldEnd} has failed the following constraints: ${boldStart}${Object.keys(this.constraints).join(`, `)}${boldEnd} \n`;
15 if (!hasParent) {
16 return (`An instance of ${boldStart}${this.target ? this.target.constructor.name : 'an object'}${boldEnd} has failed the validation:\n` +
17 (this.constraints ? propConstraintFailed(this.property) : ``) +
18 (this.children
19 ? this.children.map(childError => childError.toString(shouldDecorate, true, this.property)).join(``)
20 : ``));
21 }
22 else {
23 // we format numbers as array indexes for better readability.
24 const formattedProperty = Number.isInteger(+this.property)
25 ? `[${this.property}]`
26 : `${parentPath ? `.` : ``}${this.property}`;
27 if (this.constraints) {
28 return propConstraintFailed(formattedProperty);
29 }
30 else {
31 return this.children
32 ? this.children
33 .map(childError => childError.toString(shouldDecorate, true, `${parentPath}${formattedProperty}`))
34 .join(``)
35 : ``;
36 }
37 }
38 }
39}
40//# sourceMappingURL=ValidationError.js.map
\No newline at end of file