@@ -13,9 +13,19 @@ export type OptionalFieldOptions = FieldOptions & {
13
13
* If true, values can be omitted/undefined but not null.
14
14
*/
15
15
optional ?: boolean ;
16
- transform ?: ( value : any ) => unknown ;
16
+ transform ?: TransformerLink ;
17
17
} ;
18
18
19
+ type TransformerLink = ( prev : Transformer ) => Transformer ;
20
+ type Transformer < I = any , O = any > = ( value : I ) => O ;
21
+ export const withDefaultTransform =
22
+ (
23
+ input : TransformerLink | undefined ,
24
+ wrapping : TransformerLink ,
25
+ ) : TransformerLink =>
26
+ ( base ) =>
27
+ input ?.( wrapping ( base ) ) ?? wrapping ( base ) ;
28
+
19
29
/**
20
30
* A field that is optional/omissible/can be undefined.
21
31
* Whether it can be explicitly null is based on `nullable`.
@@ -30,19 +40,27 @@ export function OptionalField(
30
40
export function OptionalField ( ...args : any ) {
31
41
const typeFn : ( ( ) => any ) | undefined =
32
42
typeof args [ 0 ] === 'function' ? ( args [ 0 ] as ( ) => any ) : undefined ;
33
- const options : OptionalFieldOptions | undefined =
34
- typeof args [ 0 ] === 'function' ? args [ 1 ] : args [ 0 ] ;
35
- const opts = {
43
+ const options : OptionalFieldOptions =
44
+ ( typeof args [ 0 ] === 'function' ? args [ 1 ] : args [ 0 ] ) ?? { } ;
45
+ const nilIn =
46
+ options . nullable === 'items' && options . optional
47
+ ? 'itemsAndList'
48
+ : options . nullable ?? options . optional ?? true ;
49
+ const nullOut = ! ! options . nullable && options . nullable !== 'items' ;
50
+ const schemaOptions = {
36
51
...options ,
37
- nullable : options ?. nullable ?? options ?. optional ?? true ,
52
+ nullable : nilIn ,
53
+ } ;
54
+ const defaultTransformer : Transformer = ( value ) => {
55
+ if ( value === null && ! nullOut ) {
56
+ return undefined ;
57
+ }
58
+ return value ;
38
59
} ;
60
+ const finalTransformer =
61
+ options . transform ?.( defaultTransformer ) ?? defaultTransformer ;
39
62
return applyDecorators (
40
- typeFn ? Field ( typeFn , opts ) : Field ( opts ) ,
41
- Transform ( ( { value } ) => {
42
- if ( ! options ?. nullable && ( options ?. optional ?? true ) && value == null ) {
43
- return undefined ;
44
- }
45
- return options ?. transform ? options . transform ( value ) : value ;
46
- } ) ,
63
+ typeFn ? Field ( typeFn , schemaOptions ) : Field ( schemaOptions ) ,
64
+ Transform ( ( { value } ) => finalTransformer ( value ) ) ,
47
65
) ;
48
66
}
0 commit comments