From 807a9816921522c67fe79a1b81ce8564d3f9eeea Mon Sep 17 00:00:00 2001 From: Robin van Zanten Date: Tue, 27 Jul 2021 14:45:52 +0200 Subject: [PATCH] feat(project): add yupschema creator --- src/utils/yupSchemaCreator.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/utils/yupSchemaCreator.ts diff --git a/src/utils/yupSchemaCreator.ts b/src/utils/yupSchemaCreator.ts new file mode 100644 index 000000000..3430273d0 --- /dev/null +++ b/src/utils/yupSchemaCreator.ts @@ -0,0 +1,29 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import * as yupRaw from 'yup'; +import type { AnySchema } from 'yup'; +import type Reference from 'yup/lib/Reference'; +import type Lazy from 'yup/lib/Lazy'; + +const yup: any = yupRaw; + +export function createYupSchema( + schema: Record, + config: Record, +): Record | Reference | Lazy> { + const { name, validationType, validations = [] } = config; + + if (!yup[validationType] || !validations) { + return schema; + } + + let validator = yup[validationType](); + validations.forEach((validation: any) => { + const { params, type } = validation; + if (!validator[type]) { + return; + } + validator = validator[type](...params); + }); + schema[name] = validator; + return schema; +}