1
- import type { BaseSchemaAsync , Output } from '../../types.ts' ;
1
+ import type { BaseSchemaAsync , Output } from '../../types/index .ts' ;
2
2
import { getOutput } from '../../utils/index.ts' ;
3
+ import { getFallbackAsync } from '../getFallback/index.ts' ;
3
4
import type { FallbackInfo } from './types.ts' ;
4
5
5
6
/**
6
7
* Schema with fallback async type.
7
8
*/
8
9
export type SchemaWithFallbackAsync <
9
10
TSchema extends BaseSchemaAsync = BaseSchemaAsync ,
10
- TFallback extends Output < TSchema > = Output < TSchema >
11
- > = TSchema & { getFallback : ( info ?: FallbackInfo ) => Promise < TFallback > } ;
11
+ TFallback extends
12
+ | Output < TSchema >
13
+ | ( (
14
+ info ?: FallbackInfo
15
+ ) => Output < TSchema > | Promise < Output < TSchema > > ) = Output < TSchema >
16
+ > = TSchema & {
17
+ /**
18
+ * The fallback value.
19
+ */
20
+ fallback : TFallback ;
21
+ } ;
12
22
13
23
/**
14
24
* Returns a fallback value when validating the passed schema failed.
@@ -20,40 +30,21 @@ export type SchemaWithFallbackAsync<
20
30
*/
21
31
export function fallbackAsync <
22
32
TSchema extends BaseSchemaAsync ,
23
- TFallback extends Output < TSchema >
33
+ const TFallback extends
34
+ | Output < TSchema >
35
+ | ( ( info ?: FallbackInfo ) => Output < TSchema > | Promise < Output < TSchema > > )
24
36
> (
25
37
schema : TSchema ,
26
- fallback :
27
- | TFallback
28
- | ( ( info ?: FallbackInfo ) => TFallback | Promise < TFallback > )
38
+ fallback : TFallback
29
39
) : SchemaWithFallbackAsync < TSchema , TFallback > {
30
40
return {
31
41
...schema ,
32
-
33
- /**
34
- * Returns the default value.
35
- */
36
- async getFallback ( info ) {
37
- return typeof fallback === 'function'
38
- ? await (
39
- fallback as ( info ?: FallbackInfo ) => TFallback | Promise < TFallback >
40
- ) ( info )
41
- : ( fallback as TFallback ) ;
42
- } ,
43
-
44
- /**
45
- * Parses unknown input based on its schema.
46
- *
47
- * @param input The input to be parsed.
48
- * @param info The parse info.
49
- *
50
- * @returns The parsed output.
51
- */
42
+ fallback,
52
43
async _parse ( input , info ) {
53
44
const result = await schema . _parse ( input , info ) ;
54
45
return getOutput (
55
46
result . issues
56
- ? await this . getFallback ( { input, issues : result . issues } )
47
+ ? await getFallbackAsync ( this , { input, issues : result . issues } )
57
48
: result . output
58
49
) ;
59
50
} ,
0 commit comments