You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

validation.ts 705B

1234567891011121314151617181920212223242526272829
  1. import { SchemaLike, validate } from 'joi'
  2. export interface Validator {
  3. validate (data: any[] | {}): boolean
  4. }
  5. function isCustomValidator (spec: any): spec is Validator {
  6. return !!spec && !spec.isJoi && 'validate' in spec
  7. }
  8. export function ensureValidData (spec: SchemaLike | Validator | undefined, data: any, name?: string) {
  9. if (!spec) return
  10. if (isCustomValidator(spec)) {
  11. const valid = spec.validate(data)
  12. if (valid) return
  13. }
  14. const { error } = validate(data, spec)
  15. if (!error) return
  16. throw new Error(`${!!name ? name+': ': ''}Provided data {${data}} failed to meat provided spec {${spec}}`)
  17. }
  18. export { SchemaLike }
  19. export type ValdiationSpec = SchemaLike | Validator