Skip to content

Commit

Permalink
Merge pull request #14181 from nestjs/fix/validation-pipe-swc-enum-bug
Browse files Browse the repository at this point in the history
fix(common): fallback to empty string for enums when validating (swc builder)
  • Loading branch information
kamilmysliwiec authored Nov 25, 2024
2 parents 25ad5b4 + f76a693 commit f7248e2
Showing 1 changed file with 20 additions and 3 deletions.
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

0 comments on commit f7248e2

Please sign in to comment.