Skip to content

Commit d202975

Browse files
committed
Adjust OptionalField for clarity
It turns out `optional` doesn't need to be considered on the transformer out. It only helps inform if the schema should be `nullable` - allowing `null/undefined` in. `OptionalField.nullable` then widens this to further allow `nulls` into the app.
1 parent c929b2e commit d202975

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

src/common/optional-field.ts

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,19 +30,21 @@ export function OptionalField(
3030
export function OptionalField(...args: any) {
3131
const typeFn: (() => any) | undefined =
3232
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 = {
33+
const options: OptionalFieldOptions =
34+
(typeof args[0] === 'function' ? args[1] : args[0]) ?? {};
35+
const nilIn = options.nullable ?? options.optional ?? true;
36+
const nullOut = !!options.nullable;
37+
const schemaOptions = {
3638
...options,
37-
nullable: options?.nullable ?? options?.optional ?? true,
39+
nullable: nilIn,
3840
};
3941
return applyDecorators(
40-
typeFn ? Field(typeFn, opts) : Field(opts),
42+
typeFn ? Field(typeFn, schemaOptions) : Field(schemaOptions),
4143
Transform(({ value }) => {
42-
if (!options?.nullable && (options?.optional ?? true) && value == null) {
44+
if (value === null && !nullOut) {
4345
return undefined;
4446
}
45-
return options?.transform ? options.transform(value) : value;
47+
return options.transform ? options.transform(value) : value;
4648
}),
4749
);
4850
}

0 commit comments

Comments
 (0)