Skip to content
Permalink
Browse files

feat(joi): isValid, undefinedIfInvalid

  • Loading branch information...
kirillgroshkov committed Jul 8, 2019
1 parent a5cbd32 commit ecea173e5330e58391e5a12c4b0dd0ba5280d9db
Showing with 698 additions and 438 deletions.
  1. +4 −0 src/index.ts
  2. +11 −1 src/validation/joi/joi.validation.util.test.ts
  3. +21 −0 src/validation/joi/joi.validation.util.ts
  4. +662 −437 yarn.lock
@@ -54,7 +54,9 @@ import {
import { JoiValidationError } from './validation/joi/joi.validation.error'
import {
getValidationResult,
isValid,
JoiValidationResult,
undefinedIfInvalid,
validate,
} from './validation/joi/joi.validation.util'

@@ -63,6 +65,8 @@ export {
JoiValidationResult,
validate,
getValidationResult,
isValid,
undefinedIfInvalid,
Joi,
ExtendedJoi,
booleanSchema,
@@ -7,7 +7,7 @@ import {
stringSchema,
} from './joi.shared.schemas'
import { JoiValidationError } from './joi.validation.error'
import { getValidationResult, validate } from './joi.validation.util'
import { getValidationResult, isValid, undefinedIfInvalid, validate } from './joi.validation.util'

class Obj1 {
a1!: string
@@ -271,3 +271,13 @@ test('default to empty array', () => {
const _partialSchema = objectSchema<Obj1>({
a2: stringSchema,
})

test('isValid', () => {
expect(isValid('asd', stringSchema)).toBe(true)
expect(isValid(56, stringSchema)).toBe(false)
})

test('undefinedIfInvalid', () => {
expect(undefinedIfInvalid('asd', stringSchema)).toBe('asd')
expect(undefinedIfInvalid(56, stringSchema)).toBeUndefined()
})
@@ -92,6 +92,27 @@ export function getValidationResult<IN, OUT = IN> (
return vr
}

/**
* Convenience function that returns true if !error.
*/
export function isValid<IN, OUT = IN> (value: IN, schema?: AnySchemaTyped<IN, OUT>): boolean {
if (!schema) return { value } as any

const { error } = Joi.validate(value, schema, defaultOptions)
return !error
}

export function undefinedIfInvalid<IN, OUT = IN> (
value: IN,
schema?: AnySchemaTyped<IN, OUT>,
): OUT | undefined {
if (!schema) return { value } as any

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

return error ? undefined : (returnValue as any)
}

function createError (value: any, err: ValidationError, objectName?: string): JoiValidationError {
if (!err) return undefined as any
const tokens: string[] = []

0 comments on commit ecea173

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