You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
"use strict";
|
|
|
|
|
|
|
|
const matchVirtualProperty = require("@validatem/match-virtual-property");
|
|
|
|
|
|
|
|
const AggregrateValidationError = require("./aggregrate-validation-error");
|
|
|
|
|
|
|
|
// TODO: Omit the "At (root)" for path-less errors, to avoid confusion when singular values are being compared?
|
|
|
|
// TODO: Move out the path generating logic into a separate module, to better support custom error formatting code
|
|
|
|
|
|
|
|
module.exports = function aggregrateAndThrowErrors(errors) {
|
|
|
|
let rephrasedErrors = errors.map((error) => {
|
|
|
|
let stringifiedPathSegments = error.path.map((segment) => {
|
|
|
|
if (segment == null) {
|
|
|
|
throw new Error(`Unexpected empty path segment encountered; this is a bug, please report it!`);
|
|
|
|
} else if (typeof segment === "string") {
|
|
|
|
return segment;
|
|
|
|
} else if (typeof segment === "number") {
|
|
|
|
return String(segment);
|
|
|
|
} else if (matchVirtualProperty(segment)) {
|
|
|
|
return `(${segment.name})`;
|
|
|
|
} else {
|
|
|
|
throw new Error(`Unexpected path segment encountered: ${segment}; this is a bug, please report it!`);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
/* TODO: Make immutable */
|
|
|
|
let path = (stringifiedPathSegments.length > 0)
|
|
|
|
? stringifiedPathSegments.join(" -> ")
|
|
|
|
: "(root)";
|
|
|
|
|
|
|
|
error.message = `At ${path}: ${error.message}`;
|
|
|
|
return error;
|
|
|
|
});
|
|
|
|
|
|
|
|
let detailLines = rephrasedErrors.map((error) => {
|
|
|
|
return ` - ${error.message}`;
|
|
|
|
}).join("\n");
|
|
|
|
|
|
|
|
if (errors.length > 0) {
|
|
|
|
return new AggregrateValidationError(`One or more validation errors occurred:\n${detailLines}`, {
|
|
|
|
errors: rephrasedErrors
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|