UNPKG

groq-builder

Version:

A **schema-aware**, strongly-typed GROQ query builder. It enables you to build GROQ queries using **auto-completion**, **type-checking**, and **runtime validation**.

90 lines 2.78 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ValidationErrors = void 0; /** * An error that represents a list of validation errors */ class ValidationErrors extends TypeError { constructor(message = "Validation Errors", errors = []) { super(message); this.errors = errors; this.name = "ValidationErrors"; } /** * Adds a validation error to the list * * @param path - Relative path name for this error (eg. object key, array index) * @param value - Actual value at this path * @param error - The error - can be a ZodError, another ValidationError, or just any Error object */ add(path, value, error) { if (isZodError(error)) { this.errors.push(...error.errors.map((e) => ({ path: [path, ...e.path], value: value, message: e.message, }))); } else if (error instanceof ValidationErrors) { const childErrors = error.errors; childErrors.forEach((e) => { e.path.unshift(path); }); this.errors.push(...childErrors); } else { this.errors.push({ path: [path], value, message: error.message }); } } /** * Returns the number of validation errors */ get length() { return this.errors.length; } /** * Returns the error with an updated message. * This ensures we don't calculate the message * until the error is ready to be thrown. * @example * if (validationErrors.length) throw validationErrors.withMessage() */ withMessage() { const l = this.errors.length; const message = `${l} Parsing Error${l === 1 ? "" : "s"}:\n${this.errors .map((e) => `${formatPath(["result", ...e.path])}: ${e.message}`) .join("\n")}`; this.message = message; return this; } } exports.ValidationErrors = ValidationErrors; function formatPath(paths) { let res = ""; for (const p of paths) { if (p === null) continue; const needsBrace = typeof p === "number" || p === ""; if (needsBrace) { const value = typeof p === "number" ? String(p) : JSON.stringify(p); res += "[" + value + "]"; } else { if (!res) res = p; else res += "." + p; } } return res; } /** * Determines if the error is Zod-like */ function isZodError(err) { const errZ = err; return (Array.isArray(errZ.errors) && Array.isArray(errZ.issues) && typeof errZ.isEmpty === "boolean"); } //# sourceMappingURL=validation-errors.js.map