@sprucelabs/schema
Version:
Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓
98 lines (97 loc) • 3.48 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValidateErrorMessageFormatter = void 0;
const SpruceError_1 = __importDefault(require("./SpruceError"));
class ValidateErrorMessageFormatter {
constructor(error) {
if (!error) {
throw new SpruceError_1.default({
code: 'MISSING_PARAMETERS',
parameters: ['error'],
});
}
else if (error.options?.code !== 'VALIDATION_FAILED') {
throw new SpruceError_1.default({
code: 'INVALID_PARAMETERS',
parameters: ['error'],
friendlyMessage: 'Must pass a SpruceError with code of `VALIDATION_FAILED`.',
});
}
this.error = error;
}
renderError(options) {
const { fieldError, count: countOption, namePrefix } = options;
let count = countOption;
const lines = [];
const name = this.renderFieldName(fieldError, namePrefix);
if (fieldError?.errors) {
for (const error of fieldError.errors) {
lines.push(this.renderError({
fieldError: error,
count,
namePrefix: name,
}));
count++;
}
}
else {
const msg = fieldError.friendlyMessage
? `${count}. (${name}) ${fieldError.friendlyMessage}`
: `${count}. '${name}' is ${this.fieldErrorCodeToFriendly(fieldError.code)}.`;
lines.push(msg);
}
return lines.join('\n');
}
renderFieldName(fieldError, namePrefix) {
return namePrefix ? `${namePrefix}.${fieldError.name}` : fieldError.name;
}
fieldErrorCodeToFriendly(code) {
const map = {
INVALID_PARAMETER: 'invalid',
MISSING_PARAMETER: 'required',
UNEXPECTED_PARAMETER: 'was sent but should not have been',
};
return map[code];
}
getTotalErrors() {
const errors = this.error.options.errors;
const count = this.countErrors(errors);
return count;
}
countErrors(errors) {
let count = 0;
for (const error of errors) {
if (error.errors) {
count += this.countErrors(error.errors);
}
else {
count += 1;
}
}
return count;
}
renderSchemaName(shouldUseReadableNames = false) {
return shouldUseReadableNames
? (this.error.options.schemaName ?? this.error.options.schemaId)
: this.error.options.schemaId;
}
render(options) {
const totalErrors = this.getTotalErrors();
let message = options?.shouldRenderHeadline === false
? ''
: `'${this.renderSchemaName(options?.shouldUseReadableNames)}' has ${totalErrors} error${totalErrors === 1 ? '' : 's'}!\n\n`;
const errors = this.error.options.errors;
let count = 1;
const lines = [];
for (const error of errors) {
lines.push(this.renderError({ fieldError: error, count }));
count++;
}
message += lines.join('\n');
return message;
}
}
exports.ValidateErrorMessageFormatter = ValidateErrorMessageFormatter;