fix(Form): use safeParseAsync for zod (#497)

This commit is contained in:
Paul Grau
2023-08-04 19:08:04 +09:00
committed by Benjamin Canac
parent 2d6badd4b0
commit 8b19b1880e

View File

@@ -1,8 +1,11 @@
import { provide, ref, type PropType, h, defineComponent } from 'vue' import { provide, ref, type PropType, h, defineComponent } from 'vue'
import { useEventBus } from '@vueuse/core' import { useEventBus } from '@vueuse/core'
import type { ZodSchema, ZodError } from 'zod' import type { ZodSchema } from 'zod'
import type { ValidationError as JoiError, Schema as JoiSchema } from 'joi' import type { ValidationError as JoiError, Schema as JoiSchema } from 'joi'
import type { ObjectSchema as YupObjectSchema, ValidationError as YupError } from 'yup' import type {
ObjectSchema as YupObjectSchema,
ValidationError as YupError
} from 'yup'
import type { FormError, FormEvent } from '../../types' import type { FormError, FormEvent } from '../../types'
export default defineComponent({ export default defineComponent({
@@ -19,7 +22,9 @@ export default defineComponent({
required: true required: true
}, },
validate: { validate: {
type: Function as PropType<(state: any) => Promise<FormError[]>> | PropType<(state: any) => FormError[]>, type: Function as
| PropType<(state: any) => Promise<FormError[]>>
| PropType<(state: any) => FormError[]>,
default: () => [] default: () => []
} }
}, },
@@ -111,27 +116,18 @@ function isZodSchema (schema: any): schema is ZodSchema {
return schema.parse !== undefined return schema.parse !== undefined
} }
function isZodError (error: any): error is ZodError {
return error.issues !== undefined
}
async function getZodErrors ( async function getZodErrors (
state: any, state: any,
schema: ZodSchema schema: ZodSchema
): Promise<FormError[]> { ): Promise<FormError[]> {
try { const result = await schema.safeParseAsync(state)
schema.parse(state) if (result.success === false) {
return [] return result.error.issues.map((issue) => ({
} catch (error) { path: issue.path.join('.'),
if (isZodError(error)) { message: issue.message
return error.issues.map((issue) => ({ }))
path: issue.path.join('.'),
message: issue.message
}))
} else {
throw error
}
} }
return []
} }
function isJoiSchema (schema: any): schema is JoiSchema { function isJoiSchema (schema: any): schema is JoiSchema {