fortify-schema
Version:
TypeScript interface-like schema validation system that's easier to use than Zod
103 lines (100 loc) • 2.61 kB
JavaScript
'use strict';
/**
* Abstract base class for all schema types
* Provides common functionality for validation, optional/nullable handling, and defaults
*/
class BaseSchema {
constructor() {
this._optional = false;
this._nullable = false;
}
/**
* Make this field optional
*/
optional() {
this._optional = true;
return this;
}
/**
* Make this field nullable
*/
nullable() {
this._nullable = true;
return this;
}
/**
* Set default value
*/
default(value) {
this._default = value;
return this;
}
/**
* Handle common validation logic for undefined/null values
* @param value - Value to check
* @returns Validation result or null if should continue with type-specific validation
*/
handleCommonValidation(value) {
// Handle undefined
if (value === undefined) {
if (this._optional) {
return {
success: true,
data: this._default,
errors: [],
warnings: [],
};
}
return {
success: false,
data: undefined,
errors: ["Required field is missing"],
warnings: [],
};
}
// Handle null
if (value === null) {
if (this._nullable) {
return {
success: true,
data: null,
errors: [],
warnings: [],
};
}
return {
success: false,
data: undefined,
errors: ["Field cannot be null"],
warnings: [],
};
}
return null; // Continue with type-specific validation
}
/**
* Parse and validate (throws on error)
*/
parse(value) {
const result = this.validate(value);
if (!result.success) {
throw new Error(`Schema validation failed: ${result.errors.join(", ")}`);
}
return result.data;
}
/**
* Safe parse (returns result object)
*/
safeParse(value) {
return this.validate(value);
}
/**
* Create a copy of this schema with additional options
*/
clone() {
const cloned = Object.create(Object.getPrototypeOf(this));
Object.assign(cloned, this);
return cloned;
}
}
exports.BaseSchema = BaseSchema;
//# sourceMappingURL=BaseSchema.js.map