UNPKG

@sprucelabs/schema

Version:

Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓

93 lines (92 loc) • 3.38 kB
import SpruceError from './SpruceError.js'; export class ValidateErrorMessageFormatter { constructor(error) { var _a; if (!error) { throw new SpruceError({ code: 'MISSING_PARAMETERS', parameters: ['error'], }); } else if (((_a = error.options) === null || _a === void 0 ? void 0 : _a.code) !== 'VALIDATION_FAILED') { throw new SpruceError({ 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 === null || fieldError === void 0 ? void 0 : 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) { var _a; return shouldUseReadableNames ? ((_a = this.error.options.schemaName) !== null && _a !== void 0 ? _a : this.error.options.schemaId) : this.error.options.schemaId; } render(options) { const totalErrors = this.getTotalErrors(); let message = (options === null || options === void 0 ? void 0 : options.shouldRenderHeadline) === false ? '' : `'${this.renderSchemaName(options === null || options === void 0 ? void 0 : 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; } }