Skip to content

Commit

Permalink
Add support for dynamic values to withDefault
Browse files Browse the repository at this point in the history
  • Loading branch information
fabian-hiller committed Aug 21, 2023
1 parent 11d9fc7 commit f5daf91
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
5 changes: 3 additions & 2 deletions library/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ All notable changes to the library will be documented in this file.
> Note: The library has been revised and refactored. There is a migration guide in the [release notes](https://github.com/fabian-hiller/valibot/releases/tag/vX.X.X).
- Add `getPipeInfo`, `getPathInfo` and `getIssue` util (pull request #46, #92, #93)
- Add support for `boolean`, `bigint` and `symbol` to `literal` (pull request #102)
- Add `fallback` and `fallbackAsync` method (pull request #103)
- Expand `flatten` so that issues are also accepted as first argument
- Add support for `boolean`, `bigint` and `symbol` to `literal` schema (pull request #102)
- Add support for dynamic values to `withDefault` method
- Expand `flatten` method so that issues are also accepted as first argument
- Change return type of `safeParse` and `safeParseAsync` method
- Change error handling and refactor library to improve performance
- Rename `.parse` to `._parse` and `.types` to `._types` to mark it as internal API
Expand Down
11 changes: 9 additions & 2 deletions library/src/methods/withDefault/withDefault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import type { BaseSchema, BaseSchemaAsync, Input } from '../../types.ts';
*/
export function withDefault<TSchema extends BaseSchema | BaseSchemaAsync>(
schema: TSchema,
value: Input<TSchema>
value: Input<TSchema> | (() => Input<TSchema>)
): TSchema {
return {
...schema,
Expand All @@ -24,7 +24,14 @@ export function withDefault<TSchema extends BaseSchema | BaseSchemaAsync>(
* @returns The parsed output.
*/
_parse(input, info) {
return schema._parse(input === undefined ? value : input, info);
return schema._parse(
input === undefined
? typeof value === 'function'
? (value as () => Input<TSchema>)()
: value
: input,
info
);
},
};
}
Expand Down

0 comments on commit f5daf91

Please sign in to comment.