Skip to content

Commit

Permalink
feat: merge schema defaults during cast for yup and valibot
Browse files Browse the repository at this point in the history
  • Loading branch information
logaretm committed Sep 10, 2023
1 parent 51b6865 commit c372718
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
24 changes: 21 additions & 3 deletions packages/valibot/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
import { PartialDeep } from 'type-fest';
import type { TypedSchema, TypedSchemaError } from 'vee-validate';
import { Output, Input, BaseSchema, BaseSchemaAsync, safeParseAsync, safeParse, Issue } from 'valibot';
import { normalizeFormPath } from '../../shared';
import {
Output,
Input,
BaseSchema,
BaseSchemaAsync,
safeParseAsync,
safeParse,
Issue,
getDefault,
optional,
} from 'valibot';
import { isObject, merge, normalizeFormPath } from '../../shared';

export function toTypedSchema<
TSchema extends BaseSchema | BaseSchemaAsync,
Expand Down Expand Up @@ -32,8 +42,16 @@ export function toTypedSchema<
}

const result = safeParse(valibotSchema, values);
if (result.success) {
return result.data;
}

const defaults = getDefault(optional(valibotSchema));
if (isObject(defaults) && isObject(values)) {
return merge(defaults, values);
}

return result.success ? result.data : values;
return values;
},
};

Expand Down
6 changes: 6 additions & 0 deletions packages/yup/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { InferType, Schema, ValidateOptions, ValidationError } from 'yup';
import { TypedSchema, TypedSchemaError } from 'vee-validate';
import { PartialDeep } from 'type-fest';
import { isObject, merge } from '../../shared';

export function toTypedSchema<TSchema extends Schema, TOutput = InferType<TSchema>, TInput = PartialDeep<TOutput>>(
yupSchema: TSchema,
Expand Down Expand Up @@ -51,6 +52,11 @@ export function toTypedSchema<TSchema extends Schema, TOutput = InferType<TSchem
try {
return yupSchema.cast(values);
} catch {
const defaults = yupSchema.getDefault();
if (isObject(defaults) && isObject(values)) {
return merge(defaults, values);
}

return values;
}
},
Expand Down

0 comments on commit c372718

Please sign in to comment.