Validator.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { ValidationExecutor } from './ValidationExecutor';
  2. /**
  3. * Validator performs validation of the given object based on its metadata.
  4. */
  5. export class Validator {
  6. /**
  7. * Performs validation of the given object based on decorators or validation schema.
  8. */
  9. validate(objectOrSchemaName, objectOrValidationOptions, maybeValidatorOptions) {
  10. return this.coreValidate(objectOrSchemaName, objectOrValidationOptions, maybeValidatorOptions);
  11. }
  12. /**
  13. * Performs validation of the given object based on decorators or validation schema and reject on error.
  14. */
  15. async validateOrReject(objectOrSchemaName, objectOrValidationOptions, maybeValidatorOptions) {
  16. const errors = await this.coreValidate(objectOrSchemaName, objectOrValidationOptions, maybeValidatorOptions);
  17. if (errors.length)
  18. return Promise.reject(errors);
  19. }
  20. /**
  21. * Performs validation of the given object based on decorators or validation schema.
  22. */
  23. validateSync(objectOrSchemaName, objectOrValidationOptions, maybeValidatorOptions) {
  24. const object = typeof objectOrSchemaName === 'string' ? objectOrValidationOptions : objectOrSchemaName;
  25. const options = typeof objectOrSchemaName === 'string' ? maybeValidatorOptions : objectOrValidationOptions;
  26. const schema = typeof objectOrSchemaName === 'string' ? objectOrSchemaName : undefined;
  27. const executor = new ValidationExecutor(this, options);
  28. executor.ignoreAsyncValidations = true;
  29. const validationErrors = [];
  30. executor.execute(object, schema, validationErrors);
  31. return executor.stripEmptyErrors(validationErrors);
  32. }
  33. // -------------------------------------------------------------------------
  34. // Private Properties
  35. // -------------------------------------------------------------------------
  36. /**
  37. * Performs validation of the given object based on decorators or validation schema.
  38. * Common method for `validateOrReject` and `validate` methods.
  39. */
  40. coreValidate(objectOrSchemaName, objectOrValidationOptions, maybeValidatorOptions) {
  41. const object = typeof objectOrSchemaName === 'string' ? objectOrValidationOptions : objectOrSchemaName;
  42. const options = typeof objectOrSchemaName === 'string' ? maybeValidatorOptions : objectOrValidationOptions;
  43. const schema = typeof objectOrSchemaName === 'string' ? objectOrSchemaName : undefined;
  44. const executor = new ValidationExecutor(this, options);
  45. const validationErrors = [];
  46. executor.execute(object, schema, validationErrors);
  47. return Promise.all(executor.awaitingPromises).then(() => {
  48. return executor.stripEmptyErrors(validationErrors);
  49. });
  50. }
  51. }
  52. //# sourceMappingURL=Validator.js.map