Skip to content

Commit

Permalink
feat: yup helper
Browse files Browse the repository at this point in the history
  • Loading branch information
SKairinos committed Jun 30, 2023
1 parent 9da951f commit ee24c28
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions src/helpers/yup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import {
Maybe,
AnyObject,
InferType,
ValidateOptions,
ValidationError,
ObjectSchema
} from 'yup';

export function tryValidateSync<
T extends Maybe<AnyObject>,
Schema extends ObjectSchema<T>
>(
value: T,
schema: Schema,
kwArgs?: {
options?: ValidateOptions
}
): InferType<Schema> | undefined;

export function tryValidateSync<
T extends Maybe<AnyObject>,
Schema extends ObjectSchema<T>,
OnErrorRT extends InferType<Schema> | void
>(
value: T,
schema: Schema,
kwArgs?: {
options?: ValidateOptions,
onError: (error: ValidationError) => OnErrorRT
}
): OnErrorRT extends InferType<Schema>
? InferType<Schema>
: InferType<Schema> | undefined;

export function tryValidateSync<
T extends Maybe<AnyObject>,
Schema extends ObjectSchema<T>,
OnErrorRT extends InferType<Schema> | void
>(
value: T,
schema: Schema,
kwArgs?: {
options?: ValidateOptions,
onError?: (error: ValidationError) => OnErrorRT
}
): InferType<Schema> | undefined {
try {
return schema.validateSync(value, kwArgs?.options);
} catch (error) {
if (!(error instanceof ValidationError)) {
throw error;
} else if (kwArgs?.onError !== undefined) {
return kwArgs.onError(error) as InferType<Schema> | undefined;
}
}

return undefined;
}

0 comments on commit ee24c28

Please sign in to comment.