UNPKG

@decaf-ts/decorator-validation

Version:
61 lines 2.09 kB
import { BaseValidator } from "./BaseValidator.js"; import { DEFAULT_ERROR_MESSAGES } from "./constants.js"; /** * @description * Abstract class for defining asynchronous validators. * * This class extends the base `Validator` and enforces that any implementation * of `hasErrors` must be asynchronous, always returning a Promise. * * Use this when the validation process involves asynchronous operations, * such as API calls, database lookups, or time-based checks (e.g., timeouts). * * @example * ```typescript * // Example of an asynchronous validator that compares value against a timeout * class TimeoutValidator extends AsyncValidator<{ timeout?: number }> { * constructor(message: string = "Validation failed due to timeout") { * super(message); * } * * async hasErrors(value: number, options?: { timeout?: number }) { * const delay = options?.timeout ?? 100; * * // async call * await new Promise(res => setTimeout(res, delay)); * * if (value > delay) { * // Rejects the validation after waiting the delay if value is greater * return Promise.resolve(this.getMessage()); * } * * // Passes the validation after waiting the delay * return Promise.resolve(undefined); * } * } * * // Example usage: * const validator = new TimeoutValidator(); * * async function runValidation() { * const error = await validator.hasErrors(50, { timeout: 100 }); * if (error) { * return console.error('Validation error:', error); * } * console.log('Value is valid'); * } * * await runValidation(); * ``` * * - If `value > timeout`, the validator waits for the delay and then rejects with an error. * - If `value <= timeout`, the validator waits for the delay and resolves successfully with `undefined`. * * @see {@link Validator} For the base synchronous validator. */ export class AsyncValidator extends BaseValidator { constructor(message = DEFAULT_ERROR_MESSAGES.DEFAULT, ...acceptedTypes) { super(true, message, ...acceptedTypes); } } //# sourceMappingURL=AsyncValidator.js.map