Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: return promise from validation only if necessary and validate sync if possible #2417

Open
lyeq opened this issue Feb 19, 2024 · 0 comments
Labels
flag: needs discussion Issues which needs discussion before implementation. type: feature Issues related to new features.

Comments

@lyeq
Copy link

lyeq commented Feb 19, 2024

Description

The validator has public methods for asynchronous validation (validate and validateOrReject) and for synchronous validation (validateSync).
Unfortunately the synchronous method ignores all async validations while the asynchronous methods always return a pending promise.
It is therefore not possible to write a function which conditionally returns synchronously if possible and a promise if necessary.

Proposed solution

Add a method validateSyncIfPossible to class Validator which returns immediately with ValidationError[] if there are no awaiting promises and otherwise returns with Promise<ValidationError[]>.

  validateSyncIfPossible(
    objectOrSchemaName: object | string,
    objectOrValidationOptions: object | ValidationOptions,
    maybeValidatorOptions?: ValidatorOptions
  ): ValidationError[] | Promise<ValidationError[]> {

    // same as coreValidate and validateSync
    const object = typeof objectOrSchemaName === 'string' ? (objectOrValidationOptions as object) : objectOrSchemaName;
    const options =
      typeof objectOrSchemaName === 'string' ? maybeValidatorOptions : (objectOrValidationOptions as ValidationOptions);
    const schema = typeof objectOrSchemaName === 'string' ? objectOrSchemaName : undefined;

    const executor = new ValidationExecutor(this, options);
    const validationErrors: ValidationError[] = [];
    executor.execute(object, schema, validationErrors);

    // return a promise only if there are awaiting promises; otherwise return synchronously
    return executor.awaitingPromises.length === 0
      ? executor.stripEmptyErrors(validationErrors)
      : Promise.all(executor.awaitingPromises).then(() => executor.stripEmptyErrors(validationErrors));
  }
@lyeq lyeq added flag: needs discussion Issues which needs discussion before implementation. type: feature Issues related to new features. labels Feb 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
flag: needs discussion Issues which needs discussion before implementation. type: feature Issues related to new features.
Development

No branches or pull requests

1 participant