Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(common): fallback to empty string for enums when validating (swc builder) #14181

Merged
merged 2 commits into from
Nov 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions packages/common/pipes/validation.pipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,12 @@ export class ValidationPipe implements PipeTransform<any> {
: value;
}
const originalValue = value;
value = this.toEmptyIfNil(value);
value = this.toEmptyIfNil(value, metatype);

const isNil = value !== originalValue;
const isPrimitive = this.isPrimitive(value);
this.stripProtoKeys(value);

let entity = classTransformer.plainToClass(
metatype,
value,
Expand Down Expand Up @@ -208,8 +209,24 @@ export class ValidationPipe implements PipeTransform<any> {
return value;
}

protected toEmptyIfNil<T = any, R = any>(value: T): R | {} {
return isNil(value) ? {} : value;
protected toEmptyIfNil<T = any, R = any>(
value: T,
metatype: Type<unknown> | object,
): R | {} {
if (!isNil(value)) {
return value;
}
if (
typeof metatype === 'function' ||
(metatype && 'prototype' in metatype && metatype.prototype?.constructor)
) {
return {};
}
// Builder like SWC require empty string to be returned instead of an empty object
// when the value is nil and the metatype is not a class instance, but a plain object (enum, for example).
// Otherwise, the error will be thrown.
// @see https://github.com/nestjs/nest/issues/12680
return '';
}

protected stripProtoKeys(value: any) {
Expand Down
Loading