Skip to content
Permalink
Browse files

feat(validation): allow undefined schema

  • Loading branch information...
kirillgroshkov committed May 17, 2019
1 parent 429a312 commit 192e91bc9386b8235c7554474c25d86dc9c6a9f0
Showing with 22 additions and 8 deletions.
  1. +11 −0 src/validation/joi/joi.validation.util.test.ts
  2. +11 −8 src/validation/joi/joi.validation.util.ts
@@ -187,3 +187,14 @@ test('should include id in the error message', () => {
expect(error!.message).toMatchSnapshot()
expect(error!.data).toMatchSnapshot()
})

test('should return value on undefined schema', () => {
const obj = {
id: 'someId',
}

expect(validate(obj)).toBe(obj)
const { value, error } = getValidationResult(obj)
expect(value).toBe(obj)
expect(error).toBeUndefined()
})
@@ -6,7 +6,7 @@
* "Converts" mean e.g trims all strings from leading/trailing spaces.
*/

import { SchemaLike, ValidationError, ValidationOptions } from '@hapi/joi'
import { AnySchema, ValidationError, ValidationOptions } from '@hapi/joi'
import { isObject } from '@naturalcycles/js-lib'
import { Joi } from './joi.extensions'
import { JoiValidationError } from './joi.validation.error'
@@ -37,20 +37,19 @@ const defaultOptions: ValidationOptions = {
* Validates with Joi.
* Throws AppValidationError if invalid.
* Returns *converted* value.
*
* If `schema` is undefined - returns value as is.
*/
export function validate<T> (
value: T,
schema: SchemaLike,
schema?: AnySchema,
objectName?: string,
options: ValidationOptions = {},
): T {
const { value: returnValue, error } = Joi.validate(value, schema, {
...defaultOptions,
...options,
})
const { value: returnValue, error } = getValidationResult(value, schema, objectName, options)

if (error) {
throw createError(value, error, objectName)
throw error
}

return returnValue
@@ -60,13 +59,17 @@ export function validate<T> (
* Validates with Joi.
* Returns ValidationResult with converted value and error (if any).
* Does not throw.
*
* If `schema` is undefined - returns value as is.
*/
export function getValidationResult<T> (
value: T,
schema: SchemaLike,
schema?: AnySchema,
objectName?: string,
options: ValidationOptions = {},
): JoiValidationResult<T> {
if (!schema) return { value }

const { value: returnValue, error } = Joi.validate(value, schema, {
...defaultOptions,
...options,

0 comments on commit 192e91b

Please sign in to comment.
You can’t perform that action at this time.