domain-objects
Version:
A simple, convenient way to represent domain objects, leverage domain knowledge, and add runtime validation in your code base.
68 lines • 2.58 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.validate = exports.isZodSchema = void 0;
const HelpfulJoiValidationError_1 = require("./HelpfulJoiValidationError");
const HelpfulYupValidationError_1 = require("./HelpfulYupValidationError");
const HelpfulZodValidationError_1 = require("./HelpfulZodValidationError");
const isJoiSchema = (schema) => {
if (schema.$)
return true; // joi schemas have `$`, zod and yup do not
return false;
};
const isZodSchema = (schema) => {
// detect via the public `.safeParse` method (zod-only); replaces zod 3's `_refinement` internal, which was removed in zod 4 (our baseline)
if (typeof schema.safeParse === 'function')
return true;
return false;
};
exports.isZodSchema = isZodSchema;
const isYupSchema = (schema) => {
if (schema.isValidSync)
return true; // only yup schemas have this property
return false;
};
const validate = ({ domainObjectName, schema, props, }) => {
if (isJoiSchema(schema)) {
const result = schema.validate(props);
if (result.error)
throw new HelpfulJoiValidationError_1.HelpfulJoiValidationError({
domainObject: domainObjectName,
error: result.error,
props,
});
}
if (isYupSchema(schema)) {
try {
schema.validateSync(props);
}
catch (error) {
if (!(error instanceof Error))
throw error;
if (error.constructor.name === 'ValidationError')
throw new HelpfulYupValidationError_1.HelpfulYupValidationError({
domainObject: domainObjectName,
error: error,
props,
}); // if we got a yup validation error, make it more helpful
throw error; // otherwise throw the error we got
}
}
if ((0, exports.isZodSchema)(schema)) {
try {
schema.parse(props);
}
catch (error) {
if (!(error instanceof Error))
throw error;
if (error.constructor.name === 'ZodError')
throw new HelpfulZodValidationError_1.HelpfulZodValidationError({
domainObject: domainObjectName,
error: error,
props,
}); // if we got a yup validation error, make it more helpful
throw error; // otherwise throw the error we got
}
}
};
exports.validate = validate;
//# sourceMappingURL=validate.js.map