Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(Form): use safeParseAsync for zod #497

Merged
merged 1 commit into from
Aug 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 15 additions & 19 deletions src/runtime/components/forms/Form.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { provide, ref, type PropType, h, defineComponent } from 'vue'
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 { ObjectSchema as YupObjectSchema, ValidationError as YupError } from 'yup'
import type {
ObjectSchema as YupObjectSchema,
ValidationError as YupError
} from 'yup'
import type { FormError, FormEvent } from '../../types'

export default defineComponent({
Expand All @@ -19,7 +22,9 @@ export default defineComponent({
required: true
},
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: () => []
}
},
Expand Down Expand Up @@ -111,27 +116,18 @@ function isZodSchema (schema: any): schema is ZodSchema {
return schema.parse !== undefined
}

function isZodError (error: any): error is ZodError {
return error.issues !== undefined
}

async function getZodErrors (
state: any,
schema: ZodSchema
): Promise<FormError[]> {
try {
schema.parse(state)
return []
} catch (error) {
if (isZodError(error)) {
return error.issues.map((issue) => ({
path: issue.path.join('.'),
message: issue.message
}))
} else {
throw error
}
const result = await schema.safeParseAsync(state)
if (result.success === false) {
return result.error.issues.map((issue) => ({
path: issue.path.join('.'),
message: issue.message
}))
}
return []
}

function isJoiSchema (schema: any): schema is JoiSchema {
Expand Down